mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.98k stars 520 forks source link

support selecting interceptors #2071

Closed juliusmarminge closed 8 months ago

juliusmarminge commented 8 months ago

Scope

Adds a new behavior

Compatibility

Feature description

maybe there's a clear reason but why are there no options when creating the server? seems quite limiting.

for example, if i only wanna mock xml request:

const server = new SetupServerApi(handlers, {
  interceptors: [XMLHttpInterceptor]
}
kettanaito commented 8 months ago

Hi, @juliusmarminge. That's a good question!

MSW promotes the philosophy that you can describe the network regardless of the implementation details of that network. Providing a precise interceptor is not something we encourage directly because you want consistent behavior no matter how the request is made.

If you absolutely must narrow down the interception, you can do that by creating your own setupServer function using the public API:

import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'
import { SetupServerCommonApi } from 'msw/node'

class SetupXMLHttpRequestServerApi extends SetupServerCommonApi {
  constructor(...handlers) {
    super([XMLHttpRequestInterceptor], handlers)
  }
}

function mySetupServer(...handlers) {
  return new SetupXMLHttpRequestServerApi(...handlers)
}

You will be limited in the feature set, however, since SetupServerCommonApi doesn't have Node-specific features like Server Boundary. We extend the same base class for Node.js and for React Native so that base class must remain neutral.