Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature] - Vitest support #499

Open
Nick-Minutello opened this issue Jul 21, 2024 · 3 comments
Open

[feature] - Vitest support #499

Nick-Minutello opened this issue Jul 21, 2024 · 3 comments

Comments

@Nick-Minutello
Copy link

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
Copy link

ekrata-main commented Jul 23, 2024

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
Copy link

damonbauer commented Jul 28, 2024

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants