PollyJS Jest Helper
setup-polly-jest provides a testing helper that integrates PollyJS, an HTTP recording, replaying, and stubbing tool, seamlessly into Jest and Jasmine test environments. It automatically manages the lifecycle of Polly instances for individual tests and suites, simplifying setup and teardown. The current stable version is 0.11.0, indicating it's actively maintained but pre-1.0, suggesting potential API changes. It differentiates itself by abstracting away much of the boilerplate associated with PollyJS in Jest, mirroring the convenience of built-in Mocha or QUnit PollyJS helpers. It also offers custom Jest environments (node and jsdom) to ensure compatibility with different Jest runner versions, particularly jest-circus, and handles recording name generation based on test structure.
Common errors
-
You are trying to access an instance of Polly that is not yet available.
cause Attempting to access `context.polly` outside of a test hook (beforeEach, test, afterEach).fixMove the code accessing `context.polly` into a `beforeEach`, `test`/`it`, or `afterEach` block to align with Polly's lifecycle. -
ReferenceError: fetch is not defined
cause Running browser-dependent code (like `fetch` or DOM manipulation) in a Node.js test environment without a polyfill or appropriate test environment.fixIf testing browser-side code, ensure you're using `jest-environment-jsdom` (or `setup-polly-jest/jest-environment-jsdom`) in your Jest config or test file. If using Node.js `fetch`, ensure a polyfill like `node-fetch` is imported and used.
Warnings
- breaking When upgrading Jest to version 27 or higher, which uses the `jest-circus` runner by default, you must explicitly configure a custom test environment provided by `setup-polly-jest` to ensure proper integration. Failing to do so will result in tests not correctly utilizing PollyJS.
- gotcha Direct access to `context.polly` outside of test hooks (`beforeEach`, `it`/`test`, `afterEach`) will result in an error because the Polly instance is managed by the helper's lifecycle and may not yet be initialized or might already be cleaned up.
- gotcha The library's integration with Jasmine environments (used by Jest) relies on overwriting Jasmine methods. While thoroughly tested, significant changes in Jest's or Jasmine's internal test runner implementation could potentially break functionality without prior warning.
- gotcha This library has a peer dependency on `@pollyjs/core`. If `@pollyjs/core` is not installed or its version is incompatible, `setup-polly-jest` may not function correctly.
Install
-
npm install setup-polly-jest -
yarn add setup-polly-jest -
pnpm add setup-polly-jest
Imports
- setupPolly
const { setupPolly } = require('setup-polly-jest');import { setupPolly } from 'setup-polly-jest'; - Jest Environment (Node)
/** @jest-environment setup-polly-jest/jest-environment-node */
- Jest Environment (JSDOM)
/** @jest-environment setup-polly-jest/jest-environment-jsdom */
Quickstart
/** @jest-environment setup-polly-jest/jest-environment-node */
import { setupPolly } from 'setup-polly-jest';
describe('HTTP Recording with PollyJS', () => {
const context = setupPolly({
logLevel: 'info' // Example configuration option
});
beforeEach(() => {
// Intercept a specific request before the test runs
context.polly.server
.get('/api/data')
.intercept((req, res) => res.json({ message: 'Intercepted Data' }));
});
test('should be able to fetch data and use Polly', async () => {
context.polly.configure({ recordIfMissing: true });
// Simulate a network request (e.g., using node-fetch or similar)
// For a real test, you'd use your actual HTTP client (fetch, axios, etc.)
const response = await fetch('http://example.com/api/data');
const data = await response.json();
expect(response.status).toBe(200);
expect(data.message).toBe('Intercepted Data');
// The recording name is automatically generated based on suite/test names.
// Polly will stop and save the recording automatically after the test.
});
afterEach(() => {
// Optional: perform actions after Polly has done its cleanup
// For example, flushing pending requests if not handled by default stop()
context.polly.flush();
});
});