Share Your Experience With Others

Example of writing JEST Test in LWC

Here’s a simple example of how to write a Jest test in a Lightning Web Component (LWC):

  1. Create a Lightning Web Component: For this example, let’s assume you have a component named helloWorld that displays a message “Hello World”.
  2. Create a test file: In the same directory as your helloWorld component, create a new file named helloWorld.test.js. This file will contain your Jest tests.
  3. 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