{"id":15380,"library":"setup-polly-jest","title":"PollyJS Jest Helper","description":"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.","status":"active","version":"0.11.0","language":"javascript","source_language":"en","source_url":"https://github.com/gribnoysup/setup-polly-jest","tags":["javascript","polly","pollyjs","jest","jasmine","test","testing","mock","helper"],"install":[{"cmd":"npm install setup-polly-jest","lang":"bash","label":"npm"},{"cmd":"yarn add setup-polly-jest","lang":"bash","label":"yarn"},{"cmd":"pnpm add setup-polly-jest","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core PollyJS library, required for all functionality.","package":"@pollyjs/core","optional":false}],"imports":[{"note":"Primary function for configuring PollyJS within tests. Requires a modern Jest setup or transpilation for ESM syntax.","wrong":"const { setupPolly } = require('setup-polly-jest');","symbol":"setupPolly","correct":"import { setupPolly } from 'setup-polly-jest';"},{"note":"Special comment for per-file environment configuration when using jest-circus. Can also be set globally in jest.config.js.","symbol":"Jest Environment (Node)","correct":"/** @jest-environment setup-polly-jest/jest-environment-node */"},{"note":"Special comment for per-file environment configuration, particularly useful for browser-like environments with jest-circus. Can also be set globally.","symbol":"Jest Environment (JSDOM)","correct":"/** @jest-environment setup-polly-jest/jest-environment-jsdom */"}],"quickstart":{"code":"/** @jest-environment setup-polly-jest/jest-environment-node */\n\nimport { setupPolly } from 'setup-polly-jest';\n\ndescribe('HTTP Recording with PollyJS', () => {\n  const context = setupPolly({\n    logLevel: 'info' // Example configuration option\n  });\n\n  beforeEach(() => {\n    // Intercept a specific request before the test runs\n    context.polly.server\n      .get('/api/data')\n      .intercept((req, res) => res.json({ message: 'Intercepted Data' }));\n  });\n\n  test('should be able to fetch data and use Polly', async () => {\n    context.polly.configure({ recordIfMissing: true });\n\n    // Simulate a network request (e.g., using node-fetch or similar)\n    // For a real test, you'd use your actual HTTP client (fetch, axios, etc.)\n    const response = await fetch('http://example.com/api/data');\n    const data = await response.json();\n\n    expect(response.status).toBe(200);\n    expect(data.message).toBe('Intercepted Data');\n\n    // The recording name is automatically generated based on suite/test names.\n    // Polly will stop and save the recording automatically after the test.\n  });\n\n  afterEach(() => {\n    // Optional: perform actions after Polly has done its cleanup\n    // For example, flushing pending requests if not handled by default stop()\n    context.polly.flush();\n  });\n});","lang":"javascript","description":"Demonstrates setting up PollyJS in a Jest test using `setupPolly`, configuring basic interception, and verifying recorded or intercepted HTTP responses."},"warnings":[{"fix":"Add `/** @jest-environment setup-polly-jest/jest-environment-node */` (or `jsdom`) at the top of relevant test files, or configure `testEnvironment: 'setup-polly-jest/jest-environment-jsdom'` in `jest.config.js` for global application.","message":"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.","severity":"breaking","affected_versions":">=0.10.0 (with Jest >=27)"},{"fix":"Ensure all interactions with `context.polly` or `context.polly.server` occur within `beforeEach`, `test`/`it`, or `afterEach` blocks.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Regularly check the project's GitHub issues and changelog when updating Jest or related testing frameworks. Report any unexpected behavior immediately.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure `@pollyjs/core` is installed as a dev dependency (e.g., `npm install --save-dev @pollyjs/core`) and its version is compatible with `setup-polly-jest`.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Move the code accessing `context.polly` into a `beforeEach`, `test`/`it`, or `afterEach` block to align with Polly's lifecycle.","cause":"Attempting to access `context.polly` outside of a test hook (beforeEach, test, afterEach).","error":"You are trying to access an instance of Polly that is not yet available."},{"fix":"If 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.","cause":"Running browser-dependent code (like `fetch` or DOM manipulation) in a Node.js test environment without a polyfill or appropriate test environment.","error":"ReferenceError: fetch is not defined"}],"ecosystem":"npm"}