简体   繁体   中英

How to mock Axios as default export with Jest

How do I mock axios that export as default function?

I have the api helper that generalizes api request with axios()

api.js

export const callApi = (endpoint, method, data = {}) => {

  return axios({
    url: endpoint,
    method,
    data
  })
  .then((response) => // handle response)
  .catch((error) => // handle error)
};

api.spec.js

import axios from 'axios';
import { callApi } from './api';

describe('callApi()', () => {
  it('calls `axios()` with `endpoint`, `method` and `body`', () => {

    // mock axios()
    jest.spyOn(axios, 'default');

    const endpoint = '/endpoint';
    const method = 'post';
    const data = { foo: 'bar' };

    // call function
    callApi(endpoint, method, data);

    // assert axios()
    expect(axios.default).toBeCalledWith({ url: endpoint, method, data});
  });
}); 

result

Expected mock function to have been called with:
  [{"data": {"foo": "bar"}, "method": "post", "url": "/endpoint"}]
But it was not called.

The call works fine if I mock axios.get() or other methods, but not for just axios() . I don't want to change the definition of the callApi() function.

How do I mock default axios() ? What did I miss?

You cannot use jest.spyOn(axios, 'default') when you call axios directly (no default ). Changing your implementation in api.js to be axios.default(...args) makes the test pass.


A potential change you can make is to use jest.mock('axios') instead of using jest.spyOn .

import axios from 'axios';
import { callApi } from './api';

jest.mock('axios');

// Make sure to resolve with a promise
axios.mockResolvedValue();

describe('callApi()', () => {
  it('calls `axios()` with `endpoint`, `method` and `body`', () => {
    const endpoint = '/endpoint';
    const method = 'post';
    const data = { foo: 'bar' };

    // call function
    callApi(endpoint, method, data);

    // assert axios()
    expect(axios).toBeCalledWith({ url: endpoint, method, data});
  });
}); 

For jest 28 , at least, you can use the following:

import axios from 'axios'
import { myModule } from '.'

jest.mock('axios')
const mockedAxios = jest.mocked(axios, true)

describe('myModule', () => {
  test('response with no errors', async () => {
    mockedAxios.mockReturnValue('SUCCESS' as any)
    ...

    expect(mockedAxios).toHaveBeenCalledWith({
      URL: 'http://....',
      data: { update: 'data' },
      method: 'PUT',
      ...config
    })
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM