Skip to content

Instantly share code, notes, and snippets.

@manniru
Forked from alicekao/axiosMockAdapterUse.js
Created September 16, 2022 02:21
Show Gist options
  • Save manniru/d17c5a2b04fb64890249cf0988cb8702 to your computer and use it in GitHub Desktop.
Save manniru/d17c5a2b04fb64890249cf0988cb8702 to your computer and use it in GitHub Desktop.
How to use axios mock adapter
// Fetch all places action to test in actions/index.js
import axios from 'axios';
export function fetchPlaces() {
return dispatch => {
return axios.get('/api/places/fetchAll')
.then(resp => {
dispatch(updatePlaces(resp.data));
})
.catch(err => {
console.log('Couldn\'t fetch places: ', err);
dispatch(authError(err));
});
}
}
// Unit test in actions/actions.spec.js
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const mock = new MockAdapter(axios);
const expectedPlaces = [{ name: 1 }, { name: 2 }];
// Here we mock the request that will be sent by our action and send back some expected data
mock.onGet('/api/places/fetchAll').reply(200, {
data: expectedPlaces
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment