Skip to content

Instantly share code, notes, and snippets.

@alicekao
Last active May 3, 2024 09:53
Show Gist options
  • Save alicekao/59ec4f9094219efa2e831f598d9d671a to your computer and use it in GitHub Desktop.
Save alicekao/59ec4f9094219efa2e831f598d9d671a 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