jest-chrome provides a comprehensive mock of the Chrome Extension API, designed specifically for testing Chrome extensions with Jest. It aims for a complete and accurate representation of the Chrome API, with built-in TypeScript support derived directly from the `@types/chrome` package, ensuring type safety and intellisense. The package is actively maintained, with the current stable version being 0.8.0. Releases occur periodically to address Jest compatibility, improve API coverage, and fix build-related issues, though there isn't a strict time-based cadence. Its primary differentiator is the completeness of the mock and its strong adherence to the official Chrome API types, enabling robust testing of extension logic without needing a real browser environment. This allows for faster, more reliable unit and integration tests for Chrome extensions.
npm install jest-chromeVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to mock asynchronous Chrome API functions, specifically `chrome.runtime.sendMessage`, including handling callbacks and simulating `chrome.runtime.lastError` for robust error testing.
Update all `import` and `require` statements in your project from `jest-chrome` to `@extend-chrome/jest-chrome`.
Review any custom type definitions or test helpers that interact directly with Jest's mock types and update them to use `jest.MockedFunction` if necessary.
Add a `jest.setup.js` file (or similar) to your Jest configuration, and within it, use `Object.assign(global, require('jest-chrome'))`.Always provide a `mockImplementation` for asynchronous Chrome API functions (e.g., `chrome.runtime.sendMessage.mockImplementation(...)`) to define their behavior during testing.
Avoid using version 0.5.2. Upgrade to version 0.5.3 or later to ensure a stable build.
Ensure your `jest.config.js` includes `setupFilesAfterEnv: ['./jest.setup.js']` and `jest.setup.js` contains `Object.assign(global, require('jest-chrome'))`.Verify that `jest-chrome` is correctly loaded in your setup file, and that you are trying to mock a valid Chrome API method that `jest-chrome` intercepts.
Review your `mockImplementation` for asynchronous functions to ensure the callback argument is correctly invoked (e.g., `callback(response)` or `Promise.resolve(response)` if it's a promise-based API).