Playwright intercept server side network request
Asked Answered
B

1

7

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.

Brecher answered 11/2, 2022 at 15:20 Comment(0)
S
0

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

Self answered 13/2, 2022 at 19:0 Comment(4)
Thank you so much Gaj for taking the time and trying to help me out. I have updated my question with more details about what case I'm concerned about. I hope it makes sense? I don't think your solution would work since I understand is as only dealing with the client side request and responses and not the server side.Brecher
Did you manage to find a solution @Brecher ?Lull
No haven't touched playwright since.Brecher
I was trying to make this work (frontend-digest.com/…) but haven't managed to get it going - think partly this might be a versioning issue. The core method seems to be building msw into the next application (at build time, even for a test run) and then exporting the interceptor to the tests to allow overriding the server fetch. It'd be almost perfect if it could work but no luck so far (also, I don't see how it can work without building, although the author claims it can be done).Diedrediefenbaker

© 2022 - 2024 — McMap. All rights reserved.