Mocking RESTFul API in Storybook

Simulate different API responses inside Storybook stories using Axios and axios-mock-adapter.

Rafael Rozon


So, I wanted to find a way to simulate different api responses for my React components while developing them in Storybook. I found out another tutorial that was very helpful but it used another fetch library instead Axios. Then, I decided to put my own little tutorial to help others that use Storybook and Axios HTTP client.

Assuming you have Storybook already setup. Install this:

npm install axios-mock-adapter --save-dev

Then in your stories:

My Test component is just to illustrate. What is important here is:

  • Without the mock adapter, the response would be data for the planet Tatooine from the Star Wars api. But, the mock adapter intercepts the request and return { test: 'some mock data' }. Pretty cool!
  • The API call you to specify onmock.onGet has to match exactly what it’s being requested in your Axios GET call. If in doubt, check the config object of the Axios response.
  • Do not add the mock.onGet outside the .add(‘Component’, () => {...}) function because it’ll mess up other Axios calls that may be in other stories. Basically, the mock.onGet will be restricted to the scope of the story.
  • You can pass { delayResponse: 2000 }) when instantiating the axios-mock-adapter to simulate the network delay

That’s it.

Thanks and happy coding!

PS.: Here is the repo with the complete code.

Sign up for my Newsletter!

If you liked this content, sign up for my monthly newsletter. I write about
Developer Experience (DX), Frontend Development, and Software Architecture. No spam, I promise. And you can unsubscribe any time. Sign up at