mswjs / msw

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

Allow intercepting requests when tab is backgrounded #2329

Open awinograd opened 3 days ago

awinograd commented 3 days ago

Scope

Improves an existing behavior

Compatibility

Feature description

I use msw in storybook. I often switch between tabs when developing. I'll switch back and forth between storybook and figma for example to look at designs. If I look at a design, and then update my component code and save, it triggers a hot reload in storybook and my network requests will re-run. However, because the tab is backgrounded they client is filtered and will not intercept any registered requests.

https://github.com/mswjs/msw/blob/9dc2d71199021c62ad8926555c0313d3b1bd6995/src/mockServiceWorker.js#L178

This causes a minor workflow inconvenience when I switch back to the storybook tab. All network requests failed (since they are not intercepted) and I have to manually refresh the tab / story to get back to a working state.

The feature request is to add an option that allows bypassing the filtering logic above so that msw can intercept requests when the tab is backgrounded

kettanaito commented 1 day ago

Hi, @awinograd. Thanks for proposing this. That's an interesting use case.

The visibilityState check is there to distinguish between multiple active clients (tabs) when a request originates from one of them. The worker is a shared state across multiple tabs, and I believe we've added that logic to differentiate between all clients and the one that originates the request.

That check is also mostly relevant for iframes, as top-level clients will resolve immediately here:

https://github.com/mswjs/msw/blob/9dc2d71199021c62ad8926555c0313d3b1bd6995/src/mockServiceWorker.js#L163-L169

And since Storybook relies on an iframe, that's why you're hitting this problem.

Since 2.5.0, we've improved that client lookup logic, which I think should solve your use case. Can you please try that version in your setup and let me know? Thanks.

awinograd commented 21 hours ago

@kettanaito thank you for your reply. I just tried the workflow on 2.5.2 and am experiencing the same behavior. I dont think it's anything unique to my setup (aside from storybook) but let me know if it'd be helpful for me to create a reproducible repo. If so I can get to it in the next day or two

kettanaito commented 1 hour ago

@awinograd, yes, please. The repo is always welcome. Share it with me when you have the time, I will take a look. Thanks.