24

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));
});
skyboyer
  • 22,209
  • 7
  • 57
  • 64
fgonzalez
  • 3,787
  • 7
  • 45
  • 79

1 Answers1

37

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}]}))
})
shkaper
  • 4,689
  • 1
  • 22
  • 35