mswjs / msw-storybook-addon

Mock API requests in Storybook with Mock Service Worker.
https://msw-sb.vercel.app
MIT License
408 stars 39 forks source link

How to overwrite the handlers using the array definition? #114

Open BrunoQuaresma opened 1 year ago

BrunoQuaresma commented 1 year ago

Hey folks, I have a few dozen handlers being used in MSW as an array and I see to overwrite it using the addon I would have to make them "named handlers" which from the setupServer() definition is not allowed. It would also require a high amount of effort to convert them into an object map.

So is there a way to overwrite the initial global handlers in the story similar to server.use(...)? So I would not have to change my handler's definition and be able to use them on Storybook and regular tests.

Thank you!

BrunoQuaresma commented 1 year ago

Kinda of related https://github.com/mswjs/msw-storybook-addon/issues/82

kettanaito commented 2 weeks ago

Hi, @BrunoQuaresma. From my understanding of the Storybook merge algorithm, the array of request handlers you provide on the individual story level will take precedence over the base request handlers you provide to initialize(). Named handlers just allow you to disable a certain group of handlers altogether.

This is how I'd expect this to work:

initialize({}, [
  http.get('/resource', thisIsFallback)
])

export const YourStory = {
  parameters: {
    msw: {
      handlers: [
        http.get('/resource', thisTakesPrecedence),
      ]
    }
  }
}

@yannbf, please correct me if I'm wrong here. If I am, this is likely a bug and we need to look into this. Also, will check if we have tests for this use case.