Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
Salesforce QA / Tester
medium

How do you test a Lightning Web Component?

LWC has dedicated testing via Jest.

Setup:

  • sf force lightning lwc test setup — generates Jest config and setup.
  • Tests live in __tests__ folder beside component.

Anatomy:

`javascript import { createElement } from 'lwc'; import MyComponent from 'c/myComponent';

describe('c-my-component', () => { afterEach(() => { // Reset DOM between tests while (document.body.firstChild) { document.body.removeChild(document.body.firstChild); } });

it('renders a header with the title prop', () => { const element = createElement('c-my-component', { is: MyComponent }); element.title = 'Hello World'; document.body.appendChild(element);

const h1 = element.shadowRoot.querySelector('h1'); expect(h1.textContent).toBe('Hello World'); });

it('dispatches userselected event on click', () => { const element = createElement('c-my-component', { is: MyComponent }); document.body.appendChild(element);

const handler = jest.fn(); element.addEventListener('userselected', handler);

const button = element.shadowRoot.querySelector('button'); button.click();

expect(handler).toHaveBeenCalled(); expect(handler.mock.calls[0][0].detail.userId).toBe('001x'); }); }); `

Patterns:

1. Test public API only.

  • @api properties + dispatched events.
  • Don't test private state.

2. Mock Apex calls.

`javascript import getRecord from '@salesforce/apex/AccountController.getRecord'; jest.mock('@salesforce/apex/AccountController.getRecord', () => ({ default: jest.fn() }), { virtual: true });

it('renders data from Apex', async () => { getRecord.mockResolvedValue({ Id: '001x', Name: 'Acme' }); // ... render component, assert }); `

3. Mock Lightning Data Service.

Use @salesforce/sfdx-lwc-jest mocks.

4. Async resolution.

@wire resolves on next microtask. Use await Promise.resolve() between actions and assertions.

5. Snapshot tests sparingly.

  • Tempting but fragile.
  • Better: explicit assertions on key elements.

6. CI integration.

  • Jest runs in PR validation.
  • Coverage reported.
  • Failures block merge.

Common pitfalls:

  • Testing implementation details. Private methods, internal state. Brittle.
  • Real Apex calls. Tests slow, fragile. Mock instead.
  • No cleanup. Tests interfere with each other.
  • Coverage without assertions. Same as Apex problem.

Senior QA insight: LWC tests are JavaScript tests. Use JS testing patterns: AAA (Arrange/Act/Assert), mocking, async handling.

The senior framing: LWC test coverage complements Apex coverage. Together they validate the full stack.

Why this answer works

Senior. The Jest patterns and "JS testing patterns" framing are mature.

Follow-ups to expect

Related dictionary terms