Here’s a simple example of how to write a Jest test in a Lightning Web Component (LWC):
- Create a Lightning Web Component: For this example, let’s assume you have a component named
helloWorldthat displays a message “Hello World”. - Create a test file: In the same directory as your
helloWorldcomponent, create a new file namedhelloWorld.test.js. This file will contain your Jest tests. - Import the component: In your test file, import the component you want to test. For example:
import { createElement } from 'lwc';
import helloWorld from 'c/helloWorld';
4. Create a test: Use the test function provided by Jest to write a test for your component. For example:
test('displays "Hello World" message', () => {
// Create a component instance
const element = createElement('c-hello-world', { is: helloWorld });
document.body.appendChild(element);
// Get the message element
const messageEl = element.shadowRoot.querySelector('p');
// Assert that the message is "Hello World"
expect(messageEl.textContent).toBe('Hello World');
});
5. Run the test: Finally, run the test using the command npm run test or npm t. If everything is set up correctly, Jest will run the test and report the results.
This is a very simple example, but it should give you an idea of how to write Jest tests for Lightning Web Components. You can write additional tests to test different aspects of your component and ensure that it behaves as expected.
Leave a comment