Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playwright - beforeEach for all the files in the suite, or mock responses to all tests

I've seen i can mock a response in Playwright using the page.route

await page.route('https://dog.ceo/api/breeds/list/all', async route => {
  const json = {
    message: { 'test_breed': [] }
  };
  await route.fulfill({ json });
});

That's awesome, but can i do it to all tests without need to call it in each file? Is there a mock configuration in the playwright.config or something similar?

like image 910
No Idea For Name Avatar asked Sep 02 '25 17:09

No Idea For Name


1 Answers

U can use fixture for it.
Let test intercepting https://httpbin.org/uuid what normally returns {"uuid": "03840957-0386-498b-bd29-5c9cdbd84ed9"}

In file fixtures.ts:

    import { test as base } from "@playwright/test";
    
    export const test = base.extend({
      page: async ({ baseURL, page }, use) => {
        // We have a few cases where we need our app to know it's running in Playwright.
        // This is inspired by Cypress that auto-injects window.Cypress.
        await page.addInitScript(() => {
          (window as any).Playwright = true;
        });
    
        // Here we can enable logging of all requests, which is useful to see sometimes.
        // We also block some unnecessary third-party requests which speeds up the tests.
        await page.route(`https://httpbin.org/uuid`, async (route) => {
          const json = {
            message: 'my stuff 🐶',
          };
          await route.fulfill({ json });
        });
    
        use(page);
      },
    });
    export { expect } from "@playwright/test";

And then in test use new test object instead importing it form "@playwright/test"

import { test, expect } from "../fixture";

test("check if fixture working @fix", async ({ page }) => {
  // Act
  await page.goto("https://httpbin.org/uuid");
  const res = page.locator("pre");
  console.log(await res.innerText());

  // Assert
  await expect(res).toHaveText(`{"message":"my stuff 🐶"}`);
});

Finlay after running test:

Running 1 test using 1 worker
[chromium] › example.spec.ts:3:5 › check if fixture working @fix
{"message":"my stuff 🐶"}
  1 passed (1.1s)

Inspired by: https://github.com/microsoft/playwright/issues/9468#issuecomment-1403214587

like image 76
pbaranski Avatar answered Sep 05 '25 05:09

pbaranski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!