LWC Jest Unit Testing
Unit tests play a crucial role in maintaining code quality, especially in Salesforce Lightning Web Components (LWC). They help ensure that your components behave as expected.
Overview
This article will guide you through the essentials of writing unit tests for LWCs using Jest. We will cover aspects such as setting up a testing environment, writing tests, and reviewing testing outcomes.
Setting Up Jest for LWC
To get started with Jest testing in an LWC project, follow these steps:
- Install Jest: Use npm to install Jest in your project:
npm install --save-dev jest @salesforce/sfdx-lwc-jest - Configure Jest: Add a configuration file
jest.config.jsin your root directory:module.exports = { preset: '@salesforce/sfdx-lwc-jest', testPathIgnorePatterns: ["<rootDir>/.*/__tests__/.*"], }; - Create Test Files: Place your test files in a
__tests__directory adjacent to your component files.
Writing Unit Tests
Example of a Simple Test
Here's an example of a basic unit test for an LWC component:
import { createElement } from 'lwc';
import MyComponent from 'c/myComponent';
describe('c-my-component', () => {
afterEach(() => {
// Cleanup the DOM after each test
const element = document.querySelector('c-my-component');
if (element) {
element.remove();
}
});
it('renders correctly', () => {
const element = createElement('c-my-component', { is: MyComponent });
document.body.appendChild(element);
// Assert that the component is rendered
const heading = element.shadowRoot.querySelector('h1');
expect(heading).not.toBeNull();
expect(heading.textContent).toBe('Hello World');
});
});
Running Tests
Run your tests using:
npm test
Viewing Test Results
Test results will be output in your console, indicating which tests have passed or failed. Detailed reports can also be generated by configuring Jest further.
Example Test Results Visual:
Conclusion
Writing unit tests for your Lightning Web Components using Jest helps ensure the reliability and maintainability of your code. Following the patterns and examples provided can streamline your testing process.