mswjs / msw

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

fix: cannot read properties of undefined (reading 'url') #2240

Open baegofda opened 2 months ago

baegofda commented 2 months ago

fix error cannot read properties of undefined (reading 'url') (ref. https://github.com/mswjs/msw/issues/2193) image This bug is said to be fixed in the latest version, but it's still an issue for some users, including myself (I'm currently using version 2.3.5).

In the createResponseListener function, sometimes const request = context.requests.get(requestId) is possible undefined. so reference error in request.url in the code below.

if (!response.url) {
  Object.defineProperty(response, 'url', {
    value: request.url,
    enumerable: true,
    writable: false,
  })
}

The same issue does not occur when using the changed version with this code.

kettanaito commented 2 months ago

Hi, @baegofda. Thanks for opening this!

This is the issue:

sometimes const request = context.requests.get(requestId) is possible undefined

The solution you propose is a workaround. The error doesn't occur because the logic never runs. But it has to.

If you have a moment, would you look if you can spot any consistent reproduction of when context.requests.get(requestId) is undefined? I've addressed it in the past, but obviously there's more I haven't accounted for. Would be nice to track it down and fix.

baegofda commented 2 months ago

Hello, @kettanaito. Sure!

This is my Environment

Next.js 14.0.4 react: 18.2.0 msw: 2.3.5 @tanstack/react-query: 5.14.2

This is happening in my local environment where I'm developing Next.js and I'm requesting msw handler via react-query as a CSR.

In my case, the error occurs when I run more than one browser tab and do a page reload. image

baegofda commented 2 months ago

It looks like the createResponseListener return is executed before the context.requests.set in the createRequestListener.

image image

kettanaito commented 2 months ago

@baegofda, that looks interesting. Thanks for diving in! Do you have a reproduction repo where I an look at this. If I have a repro, we can track it down in no time, I believe.

econneely commented 1 week ago

Hi can this get merged still encountering this issue on latest version

artsiomshushkevich commented 1 week ago

Hi @kettanaito. msw v2.6.4 also has this issue. I was able to easily reproduce it while having multiple tabs of the same app opened.