mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.97k stars 519 forks source link

Worker.use does not work with Cypress and Vite #2341

Closed levi-cloudflare closed 3 weeks ago

levi-cloudflare commented 3 weeks ago

Prerequisites

Environment check

Browsers

Chromium (Chrome, Brave, etc.)

Reproduction repository

https://github.com/levi-cloudflare/msw-vite-cypress-bug

Reproduction steps

npm run dev # start vite dev server

then run the cypress tests:

npx cypress open

I overrode a request by adding a new handler with worker.use, but msw is discarding the new handler when it intercepts the request.

I added some console log statements, and found that even though the new handler is registered, it was being filtered out, which was why it was never used. It seems this line of code is not being evaluated correctly: https://github.com/mswjs/msw/blob/6702d778c541ebae09d5799490f645b57a12c01f/src/browser/setupWorker/start/createRequestListener.ts#L48-L52

I am not sure why handler is not being evaluated as an instanceof HttpHandler here.

Current behavior

When overriding a request by adding a new handler with worker.use, the initial handler is used instead of the new one

Expected behavior

When overriding a request by adding a new handler with worker.use, the new handler is used instead of the initial handler

levi-cloudflare commented 3 weeks ago

For some more context, here's what the prototypes look like. You can see they're from different sources, which is probably the issue, but not sure why exactly that is

Screenshot 2024-10-31 at 2 26 57 PM
levi-cloudflare commented 3 weeks ago

Ok so I realized that it's because Cypress uses webpack, but the app was built with Vite. So the HttpHandler class was coming from the Vite chunk, and the handler instance was coming from webpack (since i created the handler in the e2e test).

My solution was to store the http and HttpResponse object in window.msw so that it's always the same reference, and now it works as expected.