I just found this useful way to mock axios using jest, however, if I have multiple calls to axios with different urls, how can I specify the url and the value to be returned depending on the url? Is there any way to do it without using 3rd party libraries?
Thanks
    // users.test.js
import axios from 'axios';
import Users from './users';
jest.mock('axios');
test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  axios.get.mockResolvedValue(resp);
  // or you could use the following depending on your use case:
  // axios.get.mockImplementation(() => Promise.resolve(resp))
  return Users.all().then(data => expect(data).toEqual(users));
});
                import apis from './apis'; jest. mock('axios'); // This overwrites axios methods with jest Mock import axios from 'axios'; describe('Test Apis', () => { describe('getResource', () => { describe('with success', () => { const url = 'http://test-url.com'; const onComplete = jest.
You can handle multiple conditions in the .mockImplementation() callback:
jest.mock('axios')
axios.get.mockImplementation((url) => {
  switch (url) {
    case '/users.json':
      return Promise.resolve({data: [{name: 'Bob', items: []}]})
    case '/items.json':
      return Promise.resolve({data: [{id: 1}, {id: 2}]})
    default:
      return Promise.reject(new Error('not found'))
  }
})
test('should fetch users', () => {
  return axios.get('/users.json').then(users => expect(users).toEqual({data: [{name: 'Bob', items: []}]}))
})
test('should fetch items', () => {
  return axios.get('/items.json').then(items => expect(items).toEqual({data: [{id: 1}, {id: 2}]}))
})
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With