Node.js的新功能。我正在编写包装基础axios库的JS API客户端。在单元测试中,我使用Jest模拟axios 。
在我的API类的构造函数中,我传入一个URL,并使用该axios.create函数创建axios的自定义实例并将其绑定到client属性。
当我使用以下方法模拟axios依赖关系时会出现问题jest.mock('axios')-尝试调用时在测试中引发TypeError axios.get:
TypeError: Cannot read property `get` of undefined
Run Code Online (Sandbox Code Playgroud)
我知道为什么会这样,但是我还没有找到一种方法使我能够模拟axios并没有使client字段不确定。除了通过构造函数注入axios之外,还有其他方法可以解决此问题吗?
客户端代码和测试如下:
client.js
jest.mock("axios");
const axios = require("axios");
const mockdata = require("./mockdata");
const ApiClient = require("../../../src/clients/apiclient");
const BASE_URL = "https://www.mock.url.com"
const mockAxiosGetWith = mockResponse => {
axios.get.mockResolvedValue(mockResponse);
};
test("should make one get request", async () => {
mockAxiosGetWith(MOCK_RESPONSE)
// the client field in apiclient is undefined
// due to the jest module mocking of axios
const apiclient = …Run Code Online (Sandbox Code Playgroud)