Last active
April 26, 2023 12:29
-
-
Save rafaelrozon/ed86efbea53094726e162dc05882cddc to your computer and use it in GitHub Desktop.
Mock Axios requests in Storybook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { storiesOf } from '@storybook/react'; | |
// 1. import axios and MockAdapter | |
import axios from 'axios'; | |
import MockAdapter from 'axios-mock-adapter'; | |
// 2. create the mock | |
const mock = new MockAdapter(axios); | |
// 2.1 the api request to be intercepted has to match exactly | |
const API_REQUEST = 'https://swapi.co/api/planets/1'; | |
// 3. your component | |
class Test extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { data: {} }; | |
} | |
componentDidMount() { | |
const that = this; | |
axios.get(API_REQUEST). | |
then(function(response) { | |
that.setState({ data: response.data }) | |
}); | |
} | |
render() { | |
return ( | |
<div> | |
Response is <pre>{JSON.stringify(this.state.data, null, ' ')}</pre> | |
</div> | |
); | |
} | |
} | |
storiesOf('Mocking Api responses with Axios and axios-mock-adapter', module) | |
.add('Test', () => { | |
// 4. create the mock inside the story | |
// if this is outside it'll mess up with other axios instances/requests | |
mock.onGet(API_REQUEST).reply(200, { test: 'some mock data' }); | |
return <Test /> | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Many thanks to @ignaciojcano for your solution.
I would like to share my modified version that avoids the mock being always active in other stories.
With this approach you don't have to move
const mock = new MockAdapter(axios);
inside the stories as noted by @laurentiu1981.