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

Integration with Actions addon? #78

Closed coler-j closed 2 years ago

coler-j commented 2 years ago

It would be nice to integrate with the actions addon so request data could be made visible within the actions tab.

yannbf commented 2 years ago

This is an interesting request. @kettanaito if we want to improve the addon by providing a panel to visualize the requests, would that be doable with https://mswjs.io/docs/extensions/life-cycle-events#tracking-a-request ?

This is an example of a panel from the miragejs addon, where they show the request and response:

image

kettanaito commented 2 years ago

Hey.

You can track requests and responses as they happen using the Life-cycle API that you've linked. Add-ons like the above is precisely why such API was designed. Give it a try and let me know if there's any challenges it imposes.

yannbf commented 2 years ago

Hey.

You can track requests and responses as they happen using the Life-cycle API that you've linked. Add-ons like the above is precisely why such API was designed. Give it a try and let me know if there's any challenges it imposes.

Thank you @kettanaito! I will make some experimentations in a near future

yannbf commented 2 years ago

@coler-j I made some experimentations with addon actions and here are my findings.

You can use actions in preview.js for unhandled requests:

// .storybook/preview.js
import { action } from '@storybook/addon-actions'
import { initialize } from 'msw-storybook-addon'

initialize({
  onUnhandledRequest: (request) => {
    // very likely add an if here for requests which you don't care to track, e.g. images or fonts
    action('unhandled request')(request)
  }
})

And it looks like this:

image

And for the story, you can call the action in the callback of the MSW handler:

import { action } from '@storybook/addon-actions'

YourStory.parameters = {
  msw: [
    rest.get(YOUR_URL, (request, response, ctx) => {
      action('get request')(request) // register the action to appear in addon-actions:
      return response(ctx.json(mockData))
    }),
  ],
}

which would look like this:

image

kettanaito commented 2 years ago

I think the idea to create a panel for the add-on may be more suitable than utilizing onUnhandledRequest callback. We could hook into the request:unhandled life-cycle event instead inside the add-on, as we have access to the worker/server instance.

But first of all, we need to consider the usefulness of such a panel compared to the Network tab of the browser's devtools.