PollyJS Jest Helper

0.11.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates setting up PollyJS in a Jest test using `setupPolly`, configuring basic interception, and verifying recorded or intercepted HTTP responses.

/** @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();
  });
});

view raw JSON →