Skip to main content

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 at jest.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 from libs/vault/src/services/copy-cipher-field.service.spec.ts:

Angular Component Test

Example from libs/vault/src/components/totp-countdown/totp-countdown.component.spec.ts:

Mocking Strategies

Using jest-mock-extended

The repository uses jest-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
Example from libs/common/spec/fake-account-service.ts:

Test Setup Files

Each library can have a test.setup.ts file for custom configuration:

Coverage

Coverage is configured to:
  • Collect from all .ts files in src/ directories
  • Generate HTML and LCOV reports
  • Output to coverage/ directory
  • Use jest-junit reporter for CI integration

Best Practices

1. Test Structure

  • Use descriptive describe blocks 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-extended for type safety
  • Reset mocks between tests with beforeEach

3. Async Testing

4. Test Organization

  • Co-locate tests with source files: my-service.tsmy-service.spec.ts
  • Use nested describe blocks for complex test suites
  • Group related test cases together

5. Performance

  • Tests run with maxWorkers: 3 to prevent memory issues
  • Use isolatedModules: true for faster compilation
  • Avoid unnecessary setup in beforeEach

Common Patterns

Testing Password Reprompt

Testing Event Collection

Troubleshooting

Memory Issues

If tests crash due to memory:
  1. Check maxWorkers is set to 3
  2. Verify isolatedModules: true in ts-jest config
  3. Clear Jest cache: npm run test:watch (includes --clearCache)

Type Errors

If TypeScript types aren’t working:
  1. Ensure tsconfig.spec.json is properly configured
  2. Check moduleNameMapper paths align with tsconfig.base.json
  3. Verify all type dependencies are installed

Import Resolution

If imports fail:
  1. Check pathsToModuleNameMapper configuration
  2. Verify the prefix matches your directory structure
  3. Ensure barrel exports (index.ts) are present