首页 > 解决方案 > 如何使用 Jest 模拟 Axios 作为默认导出

问题描述

如何axios将该导出模拟为默认功能?

我有一个概括 api 请求的 api 助手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});
  });
}); 

结果

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

如果我模拟axios.get()或其他方法,调用工作正常,但不仅仅是axios(). 我不想更改callApi()函数的定义。

我如何模拟默认值axios()?我错过了什么?

标签: javascriptaxiosjestjs

解决方案


jest.spyOn(axios, 'default')直接调用时不能使用axios(否default)。将您的实现更改api.jsaxios.default(...args)使测试通过。


您可以进行的潜在更改是使用jest.mock('axios')而不是使用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});
  });
}); 

推荐阅读