Overview
The Bitwarden clients repository uses Jest as the primary testing framework for unit tests. Tests are co-located with source files using the.spec.ts naming convention.
Jest Configuration
Root Configuration
The main Jest configuration is located atjest.config.js:
Library-Level Configuration
Each library has its own Jest configuration (e.g.,libs/common/jest.config.js):
Shared Configuration
The shared Jest configuration (libs/shared/jest.config.ts.js) provides common settings:
Test Commands
Running Tests
Additional Test Commands
Test Patterns
Basic Service Test
Example fromlibs/vault/src/services/copy-cipher-field.service.spec.ts:
Angular Component Test
Example fromlibs/vault/src/components/totp-countdown/totp-countdown.component.spec.ts:
Mocking Strategies
Using jest-mock-extended
The repository usesjest-mock-extended for type-safe mocking:
Mocking Observables
Test Utilities
The repository provides test utilities in dedicated packages:@bitwarden/core-test-utils- Core testing utilities@bitwarden/state-test-utils- State management test helpers@bitwarden/storage-test-utils- Storage mocking utilities
libs/common/spec/fake-account-service.ts:
Test Setup Files
Each library can have atest.setup.ts file for custom configuration:
Coverage
Coverage is configured to:- Collect from all
.tsfiles insrc/directories - Generate HTML and LCOV reports
- Output to
coverage/directory - Use
jest-junitreporter for CI integration
Best Practices
1. Test Structure
- Use descriptive
describeblocks to group related tests - Name tests with “should” statements:
it("should return null when...") - Follow Arrange-Act-Assert pattern
2. Mocking
- Mock all external dependencies
- Use
jest-mock-extendedfor type safety - Reset mocks between tests with
beforeEach
3. Async Testing
4. Test Organization
- Co-locate tests with source files:
my-service.ts→my-service.spec.ts - Use nested
describeblocks for complex test suites - Group related test cases together
5. Performance
- Tests run with
maxWorkers: 3to prevent memory issues - Use
isolatedModules: truefor faster compilation - Avoid unnecessary setup in
beforeEach
Common Patterns
Testing Password Reprompt
Testing Event Collection
Troubleshooting
Memory Issues
If tests crash due to memory:- Check
maxWorkersis set to 3 - Verify
isolatedModules: truein ts-jest config - Clear Jest cache:
npm run test:watch(includes--clearCache)
Type Errors
If TypeScript types aren’t working:- Ensure
tsconfig.spec.jsonis properly configured - Check
moduleNameMapperpaths align withtsconfig.base.json - Verify all type dependencies are installed
Import Resolution
If imports fail:- Check
pathsToModuleNameMapperconfiguration - Verify the
prefixmatches your directory structure - Ensure barrel exports (
index.ts) are present