Norfeldt
Norfeldt

Reputation: 9638

Playwright intercept server side network request

Can't see to find any good docs on how to mock/stub the server Sider side requests with playwright.

An example would be to intercept the getServerSideProps in nextjs: hitting the routes makes the server do a request (db API etc). Then it can do some business logic (which should also be covered by testing) before it is passed to the component as props which is sent to the client (being server side rendered).

Mocking that db API request without having some test logic mixed into the business logic is what I am hoping to find an answer for.

Upvotes: 9

Views: 7448

Answers (1)

Gaj Julije
Gaj Julije

Reputation: 2163

Playwright allows you to do interception and mocking/stubbing. UI action can triger the API call, and without sending request you can intercept the response.

And you can use moks and stubs as well.

const mock = { animals: [] }

await page.route('**/Zoo/v1/books', (animals) => 
    route.fulfill({
        status: 304,
        body: JSON.stringify(mock),
    })),
);

await page.goto('https://www.demoqa/animals');

See more https://github.com/microsoft/playwright/issues/1774#issuecomment-769247500

And https://playwright.dev/docs/next/network#modify-responses

Upvotes: 0

Related Questions