Mock getServerSideProps and getStaticProps Request with MSW and Storybook Loaders

Michael Chan
InstructorMichael Chan
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we include the getServerSideProps and getStaticProps exports into a story, using Storybook loaders. We mock the fetch request using MSW.

Michael Chan: [0:00] In Storybook, we can test Next.js pages that use getServerSideProps to collect data. We do this using MSW and loaders. Here in our preview.js Storybook configuration file, we're mocking this localhost:3000/api/hello endpoint. With that in place, we can manipulate our story to use getServerSideProps. Open the stories/pages/home.

[0:28] One thing to note is that by doing this, we'll render args useless, so we can comment that out. We use loaders much like we use args. On home page, we'll add loaders and give it an array of loaders. In this case, we'll have an async function. We use a block so that we can assign a variable, let data = await getServerSideProps. Finally, we return data.props.

[1:03] Remember, getServerSideProps returns an object with props as one of the properties. Finally, we need to import getServerSideProps from that next page.

[1:19] This will load the data, but we also need to put that data on our component. Here, we'll take the second parameter, destructure loaded off of it, and the prop name. We can use name={name}.

[1:36] Sometimes, this does require a refresh on the page, but it will work. Here, we're seeing John Doh, which is coming from our getServerSideProps mock.