Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
});
like image 355
fgonzalez Avatar asked Sep 01 '19 15:09

fgonzalez


People also ask

How do you test Axios post in react?

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.


1 Answers

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}]}))
})
like image 67
shkaper Avatar answered Oct 01 '22 07:10

shkaper