Salesforce has fully embraced industry standards with Lightning Web Components and this has enabled the ability to leverage existing testing tools. Much like Mockito and ApexMocks, the Jest open source framework (https://jestjs.io/) for testing JavaScript code aims to make creating and configuring mocks as simple as possible, so your test code remains simple to read and, hence, easy to maintain. Salesforce has embraced this framework and extended it with some useful utilities and built-in mock implementations for its own components.
You can run Jest-based tests from the following command line:
npm run test:unit
The test included in this chapter should output the following:
As we did in the previous section, I always like to take a few moments away from the keyboard to think about the things I want to test and then plan out (often, in my head) the specific tests I will actually write. Each of the preceding three tests covers the behaviors listed, which we set out to cover in this Race Setup unit test.
As with Apex tests, the Jest tool automatically discovers your test code. The following code shows a cut-down version of the full test included in this chapter in order to illustrate the general structure of a test file, which is stored in the __tests__ sub-folder of the component code itself. You can name your test files anything you want, but it is best to follow a convention. Salesforce recommends suffixing the component name with .test.js:
// raceSetup.test.js
import { createElement } from 'lwc';
import RaceSetup from 'c/raceSetup';
describe('c-raceSetup', () => {
// Test: displays drivers
it('displays drivers', () => {
// Given
// Then
// When
});
// Test: add drivers success
it('add drivers success', () => {
// Given
// Then
// When
});
// Test: add drivers fail
it('add drivers fail', () => {
// Given
// Then
// When
});
});
In the following sections, we will go into more detail about each of the three preceding tests.