@salesforce/sfdx-lwc-jest to provide LWC-specific testing utilities and mocks.
Testing Setup
Jest Configuration
The project’s Jest configuration is defined injest.config.js:
- Module Name Mapping: Maps Lightning platform modules to Jest mocks for isolated testing
- Accessibility Testing: Integrates
@sa11y/jestfor automated accessibility checks - Test Timeout: Sets a 10-second timeout for asynchronous tests
Test Scripts
Thepackage.json defines several test scripts:
Writing Component Tests
Basic Component Test
Here’s a simple test example from thehello component:
Testing Wire Adapters with Parameters
Example fromapexWireMethodWithParams:
Testing Lightning Data Service APIs
Example testingcreateRecord from the Lightning Data Service:
Running Tests
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:- Runs code formatting verification with Prettier
- Executes all LWC unit tests with coverage
- Uploads coverage reports to Codecov.io
- Deploys to a scratch org and runs Apex tests
.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:
toBeAccessible() matcher for all tests, ensuring components meet WCAG accessibility standards.