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?
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.
In the latest version of MSW, everything I wrote above stands true save for the actual API you use to write the request handler:
import { http, HttpResponse } from 'msw'
http.get('/script.js', () => {
return new HttpResponse('script contents', {
headers: {
'Content-Type': 'applcation/javascript'
}
})
})
It is now more inline with the standard way how to handle requests/responses. I highly recommend reading about MSW 2.0 and following the Migration guidelines if you haven't already!