{"id":15012804,"url":"https://github.com/alectrocute/playwright-intercept","last_synced_at":"2025-04-12T03:31:52.549Z","repository":{"id":254461069,"uuid":"846605028","full_name":"alectrocute/playwright-intercept","owner":"alectrocute","description":"Ergonomically mock, wait for and assert network requests in Playwright","archived":false,"fork":false,"pushed_at":"2024-08-26T22:23:46.000Z","size":217,"stargazers_count":5,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-10-31T09:50:19.512Z","etag":null,"topics":["fixture","intercept","mock","networking","playwright","plugin"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alectrocute.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-23T15:00:58.000Z","updated_at":"2024-09-18T12:11:38.000Z","dependencies_parsed_at":"2024-08-26T18:06:07.256Z","dependency_job_id":null,"html_url":"https://github.com/alectrocute/playwright-intercept","commit_stats":null,"previous_names":["alectrocute/playwright-intercept"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alectrocute%2Fplaywright-intercept","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alectrocute%2Fplaywright-intercept/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alectrocute%2Fplaywright-intercept/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alectrocute%2Fplaywright-intercept/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alectrocute","download_url":"https://codeload.github.com/alectrocute/playwright-intercept/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223494315,"owners_count":17154526,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fixture","intercept","mock","networking","playwright","plugin"],"created_at":"2024-09-24T19:43:14.775Z","updated_at":"2024-11-07T10:04:20.954Z","avatar_url":"https://github.com/alectrocute.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# playwright-intercept 🎭\n\nThis fixture extension provides a Cypress-influenced API (like [`cy.intercept`](https://docs.cypress.io/api/commands/intercept)) for mocking and intercepting network requests in Playwright.\n\n### Features\n\n- Mock and intercept `GET`, `POST`, `PUT`, `PATCH` and `DELETE` responses\n- Craft dynamic responses at runtime using data from request params \u0026 bodies\n- Assert that requests were made to a specific URL\n- Assert the content of request bodies\n- Wait for a request to be made before continuing\n- Support for named route params (eg. `/api/:apiVersion/callback/:id`)\n- Strongly typed in TypeScript\n- Test coverage\n\n### Installation ([npm](https://www.npmjs.com/package/playwright-intercept))\n\n```bash\nnpm i playwright-intercept --save-dev\n```\n\n### Setup\n\nSimply extend your `base` test fixture with the `Intercept` class, providing optional global configuration options:\n\n- `fixturePathPrefix` is the path to your mock data folder, eg. a folder of JSON files containing default response bodies\n- To avoid Playwright log spam, `staticExtensions` are extensions of files that should never be intercepted\n\n```ts\nimport * as base from \"@playwright/test\";\nimport { Intercept } from \"playwright-intercept\";\n\nconst test = base.extend\u003cBaseFixtures\u003e({\n  intercept: async ({ page }, use) =\u003e {\n    await use(\n      new Intercept(page, {\n        fixturePathPrefix: path.join(process.cwd(), \"tests\"),\n        staticExtensions: ['js', 'css', 'png', 'jpg', 'svg'],\n      })\n    );\n  },\n});\n```\n\n### Basic Usage\n\n```ts\ntest(\"Can submit form\", async ({ page, intercept }) =\u003e {\n  // first, set up the intercept, for example:\n  const apiFormCallback = intercept.post({\n    url: \"/api/form/:id\",\n    statusCode: 200,\n    body: {\n      status: \"success\",\n    },\n    // you can also pass a file for the response body:\n    // fixture: \"path/to/response-body.json\",\n    //\n    // and modify it on the fly:\n    // modifier: ({ body, params }) =\u003e {\n    //   if (params.id === \"foo\") {\n    //     body.status = \"bar\";\n    //   }\n    //   return body;\n    // },\n    //\n    // or pass a handler function for more advanced use cases:\n    // handler: ({ route, request, params }) =\u003e {\n    //   // `route` and `request` are both normal Playwright objects\n    //   return route.fulfill({\n    //     status: 200,\n    //     contentType: 'application/json',\n    //     body: `That named route param was ${params.id}`,\n    //   });\n    // },\n  });\n\n  await page.goto(\"/my-form\");\n\n  await page.fill('input[name=\"name\"]', \"Bar\");\n\n  await page.locator(\"#submit-button\").click();\n\n  await apiFormCallback.wait();\n\n  await expect(apiFormCallback.requests[0].postDataJSON()).toBe({\n    name: \"Bar\",\n  });\n\n  apiFormCallback.update({\n    statusCode: 400,\n    body: {\n      status: \"fail\",\n    }\n  });\n\n  await page.locator(\"#submit-button\").click();\n\n  await apiFormCallback.wait();\n\n  await page.waitForSelector('div[role=\"alert\"]');\n});\n```\n\n\u003e [!TIP]  \n\u003e This repo's [`tests`](https://github.com/alectrocute/playwright-intercept/tree/main/tests) folder contains examples that demonstrate the setup and functionality of playwright-intercept.\n\n### Suggested Implementation Pattern\n\nWe recommend you create fixtures of `Intercept` instances, logically grouped together. To see this pattern demonstrated, check out [`collection-of-intercepts-as-fixture.spec.ts`](https://github.com/alectrocute/playwright-intercept/blob/main/tests/examples/collection-of-intercepts-as-fixture.spec.ts) in this repo.\n\nWe understand that everybody has their own preferred implementation pattern, so if you've found another great way to structure your `Intercept` instances in your Playwright codebase, please let us know in a PR or Issue!\n\n## API\n\n### `intercept[.get, .post, .patch, .put, .delete]`\n\n```ts\ntype BaseOptions = {\n  url: string;\n  statusCode?: number;\n};\n\ntype MimeTypeOption = {\n  mimeType?: string;\n};\n\ntype ModifierOption = {\n  modifier?: (args: {\n    body: any;\n    params: Record\u003cstring, string\u003e;\n    request: Request;\n  }) =\u003e any;\n};\n\ntype BodyOption = {\n  body: Buffer | object | string;\n};\n\ntype FixtureOption = {\n  fixture:\n    | string\n    | ((args: { route: Route; params: Record\u003cstring, string\u003e }) =\u003e string);\n};\n\ntype HandlerOption = {\n  handler: (args: {\n    route: Route;\n    params: Record\u003cstring, string\u003e;\n    request: Request;\n  }) =\u003e void;\n};\n\nexport type InterceptOptions = BaseOptions \u0026\n  (\n    | (MimeTypeOption \u0026 ModifierOption \u0026 (BodyOption | FixtureOption))\n    | HandlerOption\n    | { statusCode: number }\n  );\n```\n\nAt test runtime, `InterceptSurface` provides some methods and reactive attributes to help you assert requests.\n\n### `.wait({ timeout?: number })`\n\nResolves promise if a request has been made to the URL via selected method.\n\n```ts\nawait myIntercept.wait({ timeout: 1000 });\n```\n\n### `.requests`\n\nGives you direct access to all requests made to the URL.\n\n```ts\nexpect(myIntercept.requests[0].postData()).toEqual({\n  body: \"foo\"\n});\n\nexpect(myIntercept.requests).toHaveLength(2);\n```\n\n### `.update(InterceptOptions | (InterceptOptions) =\u003e InterceptOptions)`\n\nAllows you to change the options of an intercept post-initialization for the lifetime of the test spec.\n\n```ts\nmyIntercept.update({\n  statusCode: 400,\n  body: { id: 1 },\n});\n```\n\n## Contributing\n\nContributions are welcome! Please open [an issue](https://github.com/alectrocute/playwright-intercept/issues) or [PR](https://github.com/alectrocute/playwright-intercept/pulls) if you have any suggestions or improvements.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falectrocute%2Fplaywright-intercept","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falectrocute%2Fplaywright-intercept","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falectrocute%2Fplaywright-intercept/lists"}