Netflix / pollyjs

Record, Replay, and Stub HTTP Interactions.
https://netflix.github.io/pollyjs
Apache License 2.0
10.21k stars 352 forks source link

[feature] - Vitest support #499

Open Nick-Minutello opened 1 month ago

Nick-Minutello commented 1 month ago

Vitest is getting increasingly popular.

We were using jest, but have moved to vitest because it was much simpler/easier with Typescript & ESM modules (just works - whereas it we had lots of config trial and error trying to get jest to work, before we gave up)

We still have our polly tests stuck on jest however, as we are using setup-polly-test ....

Any plans or work in progress to support vitest ?

ekrata-main commented 1 month ago

polly + native fetch in node 20.11 with vitest is working for me

import puppeteer, { Page } from 'puppeteer';
import { vi } from 'vitest';

import FetchAdapter from '@pollyjs/adapter-fetch';
import PuppeteerAdapter from '@pollyjs/adapter-puppeteer';
import { Polly, PollyConfig } from '@pollyjs/core';
import FSPersister from '@pollyjs/persister-fs';

Polly.register(FetchAdapter);
Polly.register(FSPersister);
Polly.register(PuppeteerAdapter);

let polly: Polly;
let recordIfMissing = true;
let mode: PollyConfig['mode'] = 'replay';

switch (process.env.POLLY_MODE) {
  case 'record':
    mode = 'record';
    break;
  default:
  case 'replay':
    mode = 'replay';
    break;
  case 'offline':
    mode = 'replay';
    recordIfMissing = false;
    break;
}

/**
 * Creates a replayable recording of the api requests made in this test.
 *
 * @export
 * @param {{
 *   cassetteName: string;
 *   recordingPath: string;
 *   excludedHeaders?: string[];
 * }} param0
 * @param {string} param0.cassetteName
 * @param {*} param0.recordingPath This should be __dirname so that tests are cording in the same folder as the test calling this function.
 */
export function useCassette({
  cassetteName,
  recordingPath,
}: // excludedHeaders = [],
{
  cassetteName: string;
  recordingPath: string;
  excludedHeaders?: string[];
}) {
  beforeAll(async () => {
    polly = new Polly(cassetteName, {
      adapters: ['fetch'],
      mode,
      recordIfMissing,
      recordFailedRequests: true,
      // logLevel: 'debug',
      persister: 'fs',
      persisterOptions: {
        fs: {
          recordingsDir: `${recordingPath}/__recordings__`,
        },
      },
    });
  });

  afterAll(async () => {
    await polly.stop();
  });
  return;
}
damonbauer commented 1 month ago

polly + native fetch in node 20.11 with vitest is working for me

import puppeteer, { Page } from 'puppeteer';
import { vi } from 'vitest';

import FetchAdapter from '@pollyjs/adapter-fetch';
import PuppeteerAdapter from '@pollyjs/adapter-puppeteer';
import { Polly, PollyConfig } from '@pollyjs/core';
import FSPersister from '@pollyjs/persister-fs';

Polly.register(FetchAdapter);
Polly.register(FSPersister);
Polly.register(PuppeteerAdapter);

let polly: Polly;
let recordIfMissing = true;
let mode: PollyConfig['mode'] = 'replay';

switch (process.env.POLLY_MODE) {
  case 'record':
    mode = 'record';
    break;
  default:
  case 'replay':
    mode = 'replay';
    break;
  case 'offline':
    mode = 'replay';
    recordIfMissing = false;
    break;
}

/**
 * Creates a replayable recording of the api requests made in this test.
 *
 * @export
 * @param {{
 *   cassetteName: string;
 *   recordingPath: string;
 *   excludedHeaders?: string[];
 * }} param0
 * @param {string} param0.cassetteName
 * @param {*} param0.recordingPath This should be __dirname so that tests are cording in the same folder as the test calling this function.
 */
export function useCassette({
  cassetteName,
  recordingPath,
}: // excludedHeaders = [],
{
  cassetteName: string;
  recordingPath: string;
  excludedHeaders?: string[];
}) {
  beforeAll(async () => {
    polly = new Polly(cassetteName, {
      adapters: ['fetch'],
      mode,
      recordIfMissing,
      recordFailedRequests: true,
      // logLevel: 'debug',
      persister: 'fs',
      persisterOptions: {
        fs: {
          recordingsDir: `${recordingPath}/__recordings__`,
        },
      },
    });
  });

  afterAll(async () => {
    await polly.stop();
  });
  return;
}

This is really great, thanks @ekrata-main!

I took this a step further and tried to add sensible defaults where possible.

/**
 * Sets up Polly for recording and replaying HTTP interactions in tests.
 *
 * @param {Object} [options={}] - Configuration options for the recording.
 * @param {string} [options.recordingName] - The name of the recording. If not provided, the suite name will be used.
 * @param {string} [options.recordingPath] - The path to save the recordings. If not provided, the recordings will be saved in a "__recordings__" directory next to the test file.
 */
export function useRecording(
  options: { recordingName?: string; recordingPath?: string } = {},
) {
  beforeAll((suite) => {
    polly = new Polly(options.recordingName ?? suite.name, {
      adapters: ['fetch'],
      mode,
      recordIfMissing,
      recordFailedRequests: true,
      persister: 'fs',
      persisterOptions: {
        fs: {
          recordingsDir:
            options.recordingPath ??
            `${suite.file.filepath.substring(0, suite.file.filepath.lastIndexOf('/'))}/__recordings__`,
        },
      },
    });
  });

  beforeEach((context) => {
    // Overwrite recording name on a per-test basis
    polly.recordingName = options.recordingName ?? context.task.name;
  });

  afterAll(async () => {
    await polly.stop();
  });

  return;
}

Now, in a test, I can call useRecording() with all optional arguments:

import { describe, expect, test } from 'vitest';
import { useRecording } from '../../test-utils.js';

describe('integration', function () {
  useRecording();

  test('returns correct `posts` data', async function () {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts/2');
    const post = await res.json();

    expect(res.status).to.equal(200);
    expect(post.id).to.equal(2);
  });
});

The results:

posts/
├── __recordings__
│   ├── returns-correct-posts-data_3598317541
│   │   └── recording.har
├── posts.ts
└── posts.test.ts
Nick-Minutello commented 1 month ago

Excellent. Thanks. Got it working. I like your organisation of recordings more than the default with jest. Any chance of this making a release?