Integrate MSW and Storybook

Michael Chan
InstructorMichael Chan
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we add the Mock Service Worker (MSW) library to Storybook for API endpoint mocking in Storybook. We configure MSW by hand for use with Next.js features like getServerSideProps and getStaticProps in stories.

Michael Chan: [0:00] We can integrate MSW into our Storybook to mock API calls to Next.js endpoints. Let's stop our Storybook so that we can yarn add msw, or npm install. With MSW installed, we need to initialize it with a ServiceWorker.

[0:17] For that, we use the command, npx msw init, with a destination. We'll provide ./public --save. All this does is generate a new ServiceWorker file inside of our public directory. It warns us very clearly, not to modify it.

[0:35] With MSW initialized, we just need to edit our preview.js file in Storybook config to take advantage of it. At the top of the file, we'll import two exports from msw, setupWorker and rest. First, we do a quick check to make sure that we're in a browser -- typeof global.process === "undefined". If you have a check that you prefer, that's totally fine as well. We'll do an assignment for a new worker, called setupWorker.

[1:13] In this setupWorker() function, I want to set up a rest route. For the purposes of this demo, we'll use this local address, but these will likely be your production endpoints. Provide the handler with a request, a response, and context. Then simply return res(ctx.json()), and give it the JSON we want -- name: "John Doh". Finally, we have one last step where we need to call worker.start.

[1:48] That's it. Let's start our yarn storybook server again and validate that everything was installed correctly. Let's go to our console and if everything worked, we'll see MSW mocking in it.