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
Published 3 years ago
Updated 3 years ago

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.

egghead
egghead
~ 4 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today