A new approach to mocking GraphQL data

116 阅读1分钟

A new approach to mocking GraphQL data

How we power React component tests and examples at Stripe

Go to the profile of Sashko Stubailo
Sashko StubailoBlockedUnblockFollowFollowing
Photo by rawpixel on Unsplash

GraphQL’s main benefit for frontend developers has always been excellent tooling and developer experience. Chief among those is the ability to easily mock your data. API mocking is critical because it lets you write and test your components without having to run your whole app backend. You can even develop UI components based on a mocked schema when the backend implementation isn’t done yet, speeding up development.

In the last few months, the Dashboard Platform team at Stripe has been integrating GraphQL and Apollo for data fetching in the Stripe Dashboard. Our goal is to create a smooth and productive experience for product developers across the whole company. One of the most important aspects of that is making testing as easy as possible. In service of that outcome, we’ve come up with some new patterns that allow us to mock data with an extremely small amount of code.

I’ll tell you how we:

  1. mock GraphQL data for the whole schema
  2. customize our mocks on a per-component basis
  3. mock loading and error states with just one line of code
  4. integrate these mocks into our Jest tests and component explorer

Put together, these new tools allow us to render UI components that depend on GraphQL data in tests and examples, in all of the states that we need them, without writing code to handle specific requests and responses.

So let’s jump right in! We’ve included all of the code needed to follow along in this post. We welcome someone from the community publishing an npm package based on our approach.

Special thanks to my colleagues Isaac Hellendag, Oliver Wong, and Jason Divock, who have contributed to these tools and this post.