Mocking fetch requests in Storybook

1 June 2020
ยท
storybook
react

Install fetch-mock:

npm i --save-dev fetch-mock

And then mock your endpoint in your storybook file:

import React from 'react';
import fetchMock from 'fetch-mock';
 
import App from './index';
 
const mockTask = {
    name: 'Hello world',
}
 
export const Example = () => {
    fetchMock.restore().mock('/tasks', [mockTask]);
    return <App />;
}
 
export default { title: 'App' };

If you are on a version of Storybook older than 5.2, you will need to make use of the storiesOf API instead:

import { storiesOf } from '@storybook/react';
 
storiesOf('App', module).add('example', () => {
    fetchMock.restore().mock('/tasks', [mockTask]);
    return <App />;
});
 

Recent posts

Comments