mswjs / interceptors

Low-level network interception library.
https://npm.im/@mswjs/interceptors
MIT License
537 stars 123 forks source link

Use mswjs/interceptors as interceptors layer for Nock #425

Closed mikicho closed 2 months ago

mikicho commented 12 months ago

Hey, As part of our efforts to add fetch support to Nock, we thought we could utilize this package to intercept the requests and add Nock's great API on top of it. I'm curious how we can simulate some exotic cases as we can do in Nock, like delay the connection.

More context: https://github.com/nock/nock/issues/2397

kettanaito commented 12 months ago

Hi, @mikicho. I appreciate you reaching out.

Interceptors currently supports all means to make a request in Node.js, which includes the global Fetch API. If your testing uncovers some unexpected behaviors, it'd be a great opportunity for us to improve.

I'm curious how we can simulate some exotic cases as we can do in Nock, like delay the connection.

Sure. You can simulate a delay by awaiting a timeout promise in any request listener on the interceptor. Here's an example:

import nodePreset from '@mswjs/interceptors/presets/node'

const interceptor = new BatchInterceptor({
  name: 'my-interceptor',
  interceptors: nodePreset
})

interceptor.on('request', async ({ request }) => {
  await new Promise(resolve => setTimeout(resolve, 1000))
  request.respondWith(new Response('Hello world')
})

This example will wait for 1000ms before responding to any intercepted request with a "Hello world" mocked response. Interceptors is not opinionated in how you decide to inject such a delay. For example, with MSW 2.0, we are bringing a new delay() function that, effectively, does the above but wrapped in a nicer developer-facing API:

await delay(1000)

Your usual Promise-based sleep and such would work here too.

We can go through all the other use cases together if you could prepare a list of things Nock needs to implement.

kettanaito commented 2 months ago

The socket-based interceptor has been merged to main! 🎉 The remaining Nock-compatibility tasks are tracked in #575. Looking forward to getting the rest done!

kettanaito commented 2 months ago

I will close this in favor of https://github.com/mswjs/interceptors/issues/575.