0

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?

Carlton
  • 531
  • 1
  • 5
  • 19

2 Answers2

1

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.

kettanaito
  • 974
  • 5
  • 12
0

As per documentation of MSW, you can do so:

Providing the ctx.body() utility function with a BufferSource object will use that buffer as the mocked response's body. Support of binary data allows to send any kind of media content (images, audio, documents) in a mocked response.

molecule
  • 46
  • 3