javascript - 如何使用 Jest 将 Axios 模拟为默认导出

标签 javascript axios jestjs

如何模拟导出为默认函数的 axios

我有一个 api 帮助程序,它使用 axios()

概括 api 请求

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()?我错过了什么?

最佳答案

当你直接调用axios时,你不能使用jest.spyOn(axios, 'default')(没有default)。将 api.js 中的实现更改为 axios.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});
  });
}); 

关于javascript - 如何使用 Jest 将 Axios 模拟为默认导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52275312/

相关文章:

javascript - 使用代码中的模板实例化 WinJS.UI.ListView 时出错

javascript - 当数组与另一个数组匹配时清空数组

javascript - (this).parent().find 无法在 ajax 调用中获取响应

javascript - 如何最佳地组合多个 axios 响应

unit-testing - 如何使用Jest测试文件下载?

javascript - 在 Google Apps 脚本中迭代单选按钮值时遇到问题

javascript - Axios : unable to check login status 发出的 Drupal 和 CORS 请求

javascript - URLSearchParams 与 react-native 中的 axios 实例

reactjs - react Jest 快照测试 - 更改目录结构

jestjs - react Jest 模拟 useNavigate()