npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

playwright-msw

v3.0.1

Published

A Mock Service Worker API for Playwright.

Downloads

251,557

Readme

Features

  • Powerful. Intercept and mock network requests that are performed by browsers during Playwright test execution.
  • Customizable. Runs within context of an individual test, mocks can be safely manipulated on a per-test basis without interfering with others that are executing in parallel.
  • Flexible. Like the official MSW library that runs within the browser, playwright-msw supports both REST and GraphQL.
  • Easy to implement. No code changes are required to your app. [^implementation]

[^implementation]: If the target application is already running MSW in the browser (e.g. a local dev server), this will need to be disabled while the Playwright tests are executing. It is recommended to test against the production bundle.

Announcement

As of version 3, playwright-msw has been updated to utilize MSW 2.x. In order to utilize the latest version of playwright-msw, you must update your tests to use the new syntax. Please follow MSW's amazing Migration Guide. Apart from updating your tests to use MSW's new syntax, the API for playwright-msw itself remains unchanged.

If you're not ready to update your tests, please continue to use version 2.x of playwright-msw.

Getting started

Prerequisites

This library assumes that you have the following peer dependencies are already installed:

Install

To start, install the dependency using your preferred package manager:

npm install playwright-msw --save-dev
# or
yarn add playwright-msw --dev

Setup

Create mock handlers

If you haven't already done so, create some mock handlers for API calls that your app will perform. e.g. within a handlers.ts file:

import { http, delay, HttpResponse } from 'msw';

/** A collection of handlers to be used by default for all tests. */
export default [
  http.get('/api/users', async () => {
    await delay(500);
    return HttpResponse.json(
      [
        {
          id: 'bcff5c0e-10b6-407b-94d1-90d741363885',
          firstName: 'Rhydian',
          lastName: 'Greig',
        },
        {
          id: 'b44e89e4-3254-415e-b14a-441166616b20',
          firstName: 'Alessandro',
          lastName: 'Metcalfe',
        },
        {
          id: '6e369942-6b5d-4159-9b39-729646549183',
          firstName: 'Erika',
          lastName: 'Richards',
        },
      ],
      {
        status: 200,
      },
    );
  }),
];

Create a the worker fixture

The next step is to create a custom fixture using the createWorkerFixture function from playwright-msw. e.g. within a custom test.ts file:

If you're using REST API's, all you need to do is provide your handlers to createWorkerFixture, no config object is required:

import { test as base, expect } from '@playwright/test';
import { http } from 'msw';
import type { MockServiceWorker } from 'playwright-msw';
import { createWorkerFixture } from 'playwright-msw';

import handlers from './handlers';

const test = base.extend<{
  worker: MockServiceWorker;
  http: typeof http;
}>({
  worker: createWorkerFixture(handlers),
  http
});

export { expect, test };

Note: if you're using GraphQL, then it is assumed that the calls are made over HTTP. The default uri for the graphql endpoint is /graphql. This can be customized via configuration object when creating the worker.

Use the custom test fixture

The final step is to use the extended test implementation within your playwright tests. e.g. within a http.spec.ts file:

import { delay, HttpResponse } from 'msw';
import { expect, test } from '../test';

test.describe.parallel("A demo of playwright-msw's functionality", () => {
  test('should use the default handlers without requiring handlers to be specified on a per-test basis', async ({
    page,
  }) => {
    await page.goto('/');
    await expect(page.locator('text="Alessandro Metcalfe"')).toBeVisible();
  });

  test.only('should allow mocks to be overridden on a per test basis', async ({
    page,
    worker,
    http
  }) => {
    await worker.use(
      http.get('/api/users', async () => {
        await delay(250);
        return new HttpResponse(null, {
          status: 403,
        });
      }),
    );
    await page.goto('/');
    await expect(page.locator('text="Alessandro Metcalfe"')).toBeHidden();
    await expect(page.locator('text="Failed to load users"')).toBeVisible();
  });
});

API

createWorkerFixture

The createWorkerFixture(handlers, config) function creates a fixture that mocks api calls on a per-test basis that is automatically started even if the test does not use it directly. The provided handlers will be used by all tests by default. The created MockServiceWorker fixture can be optionally used to customise mocks on a per-test basis.

Refer to the Getting Started: Create a the worker fixture for a usage example. If this abstraction layer is over-simplified for your use case, the createWorker function can be used instead.

Configuration

The createWorkerFixture function supports an optional configuration object with the following parameters:

| key | required | default | description | | --------------- | -------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | graphqlUrl | false | "/graphql" | The URL of the GraphQL endpoint to send requests to. | | waitForPageLoad | false | true | Waits for the page to load before mocking API calls. When enabled, it allows playwright-msw to mirror the behaviour of msw when it is running in the browser, where the initial static resource requests will not be mocked because msw will have only been initialized until after page load. |

When enabled, it allows playwright-msw to emulate the behavior of msw when running in the browser, i.e. initialize after page load |

createWorker

The createWorker(page: Page, handlers?: RequestHandler[], config?: Config) function creates a server that intercepts and mocks API calls for an individual playwright page. It returns a MockServiceWorker object which can be used for further customization.

Usage example:

import { test as base, expect } from '@playwright/test';
import { createWorker, MockServiceWorker } from 'playwright-msw';

import handlers from './handlers';

const test = base.extend<{
  worker: MockServiceWorker;
}>({
  worker: [
    async ({ page }, use) => {
      const server = await createWorker(page, handlers);
      // Test has not started to execute...
      await use(server);
      // Test has finished executing...
      // [insert any cleanup actions here]
    },
    {
      /**
       * Scope this fixture on a per test basis to ensure that each test has a
       * fresh copy of MSW. Note: the scope MUST be "test" to be able to use the
       * `page` fixture as it is not possible to access it when scoped to the
       * "worker".
       */
      scope: 'test',
      /**
       * By default, fixtures are lazy; they will not be initalised unless they're
       * used by the test. Setting `true` here means that the fixture will be auto-
       * initialised even if the test doesn't use it.
       */
      auto: true,
    },
  ],
});

export { test, expect };

MockServiceWorker

The MockServiceWorker instance returned by createWorker or exposed via createWorkerFixture has a number of utility functions to facilitate additional customisations:

  • use(...customHandlers: RequestHandler[]): Prepends given request handlers to the list of existing handlers. This is useful for overriding mocks on a per test behaviour, e.g. testing what happens if a particular API call fails.
  • resetHandlers(...customHandlers: RequestHandler[]): Resets request handlers to the initial list given to the createWorker call, or to the explicit next request handlers list, if given.
  • resetCookieStore(): Resets MSW's internal cookie store by removing all cookies from it. *Note: this is automatically called at the end of each test.*

Examples

This library tests itself to make sure the integration between MSW and Playwright is working as expected. For real examples of how it can be used, please refer to: packages/example/README.md

Acknowledgements

This library does not seek to steal any thunder, it merely unifies two amazing tools that have already been built:

  1. kettanaito for creating MSW
  2. Microsoft for creating Playwright

Thank you for making these tools and thank you to the numerous people who have contributed to playwright-msw 🙂

Footnotes