How to mock third-party resources loaded in the <head>? Wait for the worker to start before document request? #463
-
The documentation did a good job of warning me that <!-- not sure if I'm using these attributes correctly, blocking ESM is confusing -->
<script blocking="render" async type="module" src="/mock-third-party-script.js"></script>
<script async type="module" src="https://third-party.com/script.js"></script> where However, I don't understand how to make it work. I could, inject the script after the promise is resolved, but I would like my mock to be unobtrusive, so that I can comment it out or uncomment it as I please. Is there a way to wait for worker to start, and only get the browser to do the intended document request? I looked at the Epic Stack, but they seem to do it at the server level, which wouldn't work for third-party resources AFAIK. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hi, @silvenon. I believe you have to get the worker registered first, then once it is, as long as those resources issue a fetch request, you should be able to define a request handler for it in MSW and handle them. |
Beta Was this translation helpful? Give feedback.
Yeah, I think this is just one of those limitations of service workers. Handler updates don't require worker updates so you are free to edit your mocking logic and have no race conditions again after the worker has registered the first time. The worker only ever needs to re-register when the worker script itself changes (e.g. you update MSW).