I've been using MSW to intercept REST api calls and mock responses. However I am wanting to intercept a JS file (e.g. "/some-file.js") and override its content. Is this possible using MSW handlers?
2 Answers
Yes and no.
You can mock almost anything in the context of asynchronous requests. For example, you can mock a /script.js
if your application is fetching that resource.
rest.get('/script.js', (req, res, ctx) => {
return res(ctx.text('script contents'), ctx.set('Content-Type', 'application/javascript'))
})
You cannot mock static assets, however. First of all, certain static asset requests are synchronous or otherwise unavailable to the worker, if the memory serves me right, like a /image.png
requested by the src
attribute of an <img />
.
Mock Service Worker comes with an intentional design to prevent you from intercepting initial application assets, like its index.html
, JavaScript modules or CSS files. This is done to prevent the developer from accidentally breaking their application by overriding initial assets. So, if you wish to intercept and mock something like <script src="script.js">
, that won't be possible.

- 974
- 5
- 12