Overriding MSW handlers in Playwright #1322
|
Hey @kettanaito & maintainers! I have a use case where I run programatic Playwright executions where I need to overwrite the MSW handlers in the following fashion: const context = await browser.newContext();
const page = await context.newPage();
await page.evaluate(()=>{
const { worker, rest } = window.msw;
worker.use(
rest.post('/login', (req, res, ctx) => {
return res(ctx.json({ success: true }))
}),
)
// expect runtime msw /login route to return mocked response now, even thought this handler has not being defined in advance
})I think Playwright does not have the |
Replies: 3 comments 8 replies
|
Hey, @d-ivashchuk.
I think that's the main culprit. You need to set // src/index.js
// Also a pseudo-code, please refer to the docs!
worker.start()
window.worker = worker // <- thisWhen Playwright opens your app, it will have Given that everything you send to Playwright from the test undergoes serialization, the best option is to set |
|
Another way to easily override handlers on a per test basis in Playwright is to use my playwright-msw library. This library utilises fixtures with routes to facilitate mocking API calls on a per test basis instead of the An example of what this mocking looks like can be seen in the docs: If you're interested, feel free to try the library out and reach out if you have any questions 🙂 |
|
The application I'm currently working uses react query, if an action is triggered to change the status of a card and it is sucessful, I invalidate the query for the list to refetch, and then I wanted the new data to show. I tried to use the dynamic mock scenarios, but then the first request to the list would come with the status I wanted after triggering the action. To solve this problem, I used playwright addExtraHeaders method from the fixture I had to add page.setExtraHTTPHeaders({}) at the end of my test otherwise other tests would use those headers and the list would be different for other assertions, causing some tests to fail. Hope that helps anyone who came to this discussion because tried worker.use() inside playwright |
Hey, @d-ivashchuk.
I think that's the main culprit. You need to set
window.mswin your browser context. For example, when opening an app with Playwright, you'd have to go through the Browser integration of MSW in your app:When Playwright opens your app, it will have
window.mswbecause your application sets it.Given that everything you send to Playwright from the test undergoes serialization, the best option is to set
window.mswin your application directly (you …