【问题标题】:How to mock Axios as default export with Jest如何使用 Jest 模拟 Axios 作为默认导出
【发布时间】:2019-02-15 22:08:19
【问题描述】:

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

我有一个使用axios()概括api请求的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()?我错过了什么?

【问题讨论】:

  • 方法接受 Object{method: 'post'} 一样,但我可以看到您将它作为普通值而不是对象传递。
  • return axios({ url: endpoint, method: postmethod, data }) 试试这个
  • 我没有收到评论。 callApi() 接受普通值。然后它从其纯值参数构造对象并将对象传递给axios()。这就是你想要指出的吗?
  • 是的,我没有看到 method 转换为 callApi 中的对象。
  • 属性同名时的简写对象赋值。这意味着const foo = { method: method }const foo = { method } 相同。或者如果我错过了任何一点?

标签: javascript axios jestjs


【解决方案1】:

当您直接调用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});
  });
}); 

【讨论】:

  • 谢谢。虽然有一个问题,axios.mockImplementation 工作正常,但我在axios.mockResolvedValue 上有一个错误,指出_axios2.default.mockResolvedValue is not a function。开玩笑版23.6.0.
  • 23.6 中肯定有这个功能。你在用create-react-app吗?在这种情况下,除非您弹出,否则您将一直停留在 Jest 20 上,直到它们升级为止。如果你不使用 CRA,我不知道出了什么问题......
  • 我正在使用样板 React Slingshot
  • 用 axios.mockResolvedValue() 救了我的命。我找到了模拟 axios 但没有提到这一点的例子。谢谢!
  • 这在 2021 年对我不起作用。我想知道为什么?
猜你喜欢
  • 2019-04-16
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2018-03-20
  • 2022-07-21
  • 1970-01-01
  • 2019-06-12
相关资源
最近更新 更多