Skip to main content
Lightning Web Components Recipes uses Jest as the testing framework for unit testing LWC components. The project leverages @salesforce/sfdx-lwc-jest to provide LWC-specific testing utilities and mocks.

Testing Setup

Jest Configuration

The project’s Jest configuration is defined in jest.config.js:
Key configuration features:
  • Module Name Mapping: Maps Lightning platform modules to Jest mocks for isolated testing
  • Accessibility Testing: Integrates @sa11y/jest for automated accessibility checks
  • Test Timeout: Sets a 10-second timeout for asynchronous tests

Test Scripts

The package.json defines several test scripts:

Writing Component Tests

Basic Component Test

Here’s a simple test example from the hello component:

Testing Wire Adapters with Parameters

Example from apexWireMethodWithParams:

Testing Lightning Data Service APIs

Example testing createRecord from the Lightning Data Service:

Running Tests

1

Run all unit tests

2

Run tests in watch mode

For continuous testing during development:
3

Generate code coverage report

Coverage reports are generated in the coverage/ directory.
4

Debug tests

To debug tests in Chrome DevTools:

Testing Best Practices

1. Clean Up After Each Test

Always clean up the DOM after each test to prevent test pollution:

2. Use Async/Await for Promise Handling

Create a helper function for flushing promises:

3. Mock External Dependencies

Always mock Apex controllers, Lightning platform modules, and external libraries:

4. Test Accessibility

Include accessibility tests for every component:

5. Use Realistic Mock Data

Store mock data in JSON files in the __tests__/data/ directory for better maintainability.

6. Test Error States

Always test both success and error scenarios:

7. Test User Interactions

Simulate user interactions to test event handlers:

Continuous Integration

The project runs tests automatically in CI using GitHub Actions. The workflow:
  1. Runs code formatting verification with Prettier
  2. Executes all LWC unit tests with coverage
  3. Uploads coverage reports to Codecov.io
  4. Deploys to a scratch org and runs Apex tests
See .github/workflows/ci.yml for the complete CI configuration.

Accessibility Testing

The project uses @sa11y/jest for automated accessibility testing. The setup is configured in jest-sa11y-setup.js:
This enables the toBeAccessible() matcher for all tests, ensuring components meet WCAG accessibility standards.