Newer Version Available
Write Your Own Tests
While working with Lightning components, consider writing tests for the following.
- DOM rendering
- Validate that components are added where and when they should be.
- Component state
- Ensure that components respond as expected.
- Server-side callback response
- Get the right response from a call to another service or resource.
- Validation of variables
- Do you have variable values that load from other sources, especially remote ones? Make sure that they do.
- Conditional UI rendering
- Verify what users see when you want them to see it.
- Event Handling
- Test responses to events.
Fortunately, the LightningTestingService Github repo contains examples of all of these cases in the staticresources directory for both Jasmine and Mocha testing frameworks.
Jasmine is well documented here: https://jasmine.github.io and provides a simple setup.
Mocha is well documented here: https://mochajs.org. Mocha is newer and might require some plugins to get the results you want. Both test frameworks use a describe...it block structure.
Use an it function to define what you’re testing, and what you expect (or explicitly don’t expect) to happen. To provide a name for the test, wrap each function in a describe block. Group it functions together within the block. Grouped functions can share variables and other values within the block.
1describe("A suite that passes", function() {
2 it("spec that verifies that true is true", function() {
3 expect(true).toBe(true);
4 });
5 it("spec that verifies that false is false", function() {
6 expect(false).toBe(false);
7 });
8});You could rearrange the test to have both it functions within the one describe function, or also test for the negative case: expect(true).not.toBe(false);
You have several options to get similar results. The key is to focus on the outcome of the it function.
For example, the jasmineHelloWorldTests.resource contains a unit test that validates a state change.
1describe('c:egComponentMethod', function() {
2 it("updates an attribute value when a method is invoked on the component's interface", function(done) {
3 $T.createComponent("c:egComponentMethod", null)
4 .then(function(component) {
5 component.sampleMethod();
6 expect(component.get("v.status")).toBe("sampleMethod invoked");
7 done();
8 }).catch(function(e) {
9 done.fail(e);
10 });
11 });
12});When you’ve written your test suite, use the CLI to push and run the tests.
Use the $T Utility Object
LTS includes the $T utility object. This object has methods that simplify routine testing operations. In the example above, the $T.createComponent() method creates the component with the descriptor c:egComponentMethod with no specific attributes. However, you can use the $T.createComponent() method to add attributes or insert the component into the DOM.
Learn more
The LightningTestingService Github repo has ongoing solutions and discussions of known issues.