Security News
cURL Project and Go Security Teams Reject CVSS as Broken
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
playwright-msw
Advanced tools
A Mock Service Worker (MSW) integration layer for Playwright.
This library assumes that you have the following peer dependencies are already installed:
To start, install the dependency using your preferred package manager:
npm install playwright-msw --save-dev
# or
yarn add playwright-msw --dev
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 { rest } from "msw";
/** A collection of handlers to be used by default for all tests. */
export default [
rest.get("/api/users", (_, response, context) =>
response(
context.delay(500),
context.status(200),
context.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",
},
])
)
),
];
The next step is to create a custom fixture using the createWorkerFixture function from playwright-msw
. e.g. within a custom test.ts file:
import { test as base, expect } from "@playwright/test";
import type { MockServiceWorker } from "playwright-msw";
import { createWorkerFixture } from "playwright-msw";
import handlers from "./handlers";
const test = base.extend<{
worker: MockServiceWorker;
}>({
worker: createWorkerFixture(...handlers),
});
export { test, expect };
The final step is to use the extended test
implementation within your playwright tests. e.g. within a demo.spec.ts file:
import { rest } 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,
}) => {
await worker.use(
rest.get("/api/users", (_, response, context) =>
response(context.delay(250), context.status(403))
)
);
await page.goto("/");
await expect(page.locator('text="Alessandro Metcalfe"')).toBeHidden();
await expect(page.locator('text="Failed to load users"')).toBeVisible();
});
});
The createWorkerFixture(...handlers)
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 createServer function can be used instead.
The createServer(page: Page, ...handlers: RequestHandler[])
function creates a server that intercepts and mocks API calls for an individual playwright page. The createServer
returns a MockServiceWorker object which can be used for further customization.
Usage example:
import { test as base, expect } from "@playwright/test";
import { createServer, MockServiceWorker } from "playwright-msw";
import handlers from "./handlers";
const test = base.extend<{
worker: MockServiceWorker;
}>({
worker: [
async ({ page }, use) => {
const server = await createServer(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 };
The MockServiceWorker
instance exposes 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 createServer call, or to the explicit next request handlers list, if given.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. ↩
FAQs
A Mock Service Worker API for Playwright.
The npm package playwright-msw receives a total of 53,902 weekly downloads. As such, playwright-msw popularity was classified as popular.
We found that playwright-msw demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.