fgonzalez
fgonzalez

Reputation: 3877

Using jest to mock multiple axios calls

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));
});

Upvotes: 26

Views: 23955

Answers (1)

shkaper
shkaper

Reputation: 4988

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}]}))
})

Upvotes: 41

Related Questions