node.js 的新手。我正在编写一个包装底层 axios 的 JS API 客户端图书馆。在单元测试中,我使用 Jest 模拟 axios .
在我的 API 类的构造函数中,我传入一个 URL,并使用 axios.create
函数来创建 axios 的自定义实例并将其绑定(bind)到客户端属性。
当我使用 jest.mock('axios')
模拟 axios 依赖项时出现问题 - 当尝试调用 axios.get 时在测试中抛出 TypeError
:
TypeError: Cannot read property `get` of undefined
我明白为什么会这样,但我还没有找到一种方法来让我模拟 axios 并且不让客户端字段未定义。除了通过构造函数注入(inject) 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 = new ApiClient.AsyncClient(BASE_URL);
// TypeError: Cannot read property `get` of undefined
return await apiclient.get("something").then(response => {
expect(axios.get).toHaveBeenCalledTimes(1);
});
});
client.test.js
const axios = require("axios");
const getClient = (baseUrl = null) => {
const options = {
baseURL: baseUrl
};
const client = axios.create(options);
return client;
};
module.exports = {
AsyncClient: class ApiClient {
constructor(baseUrl = null) {
this.client = getClient(baseUrl);
}
get(url, conf = {}) {
return this.client
.get(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
}
};
最佳答案
你需要模拟 axios
所以它将返回一个包含 create
的对象应该返回带有 get
的对象的函数
import axios from 'axios'
jest.mock('axios', () => ({create: jest.fn()}))
test("should make one get request", async () => {
const get = jest.fn(()=>Promise.resolve(MOCK_RESPONSE))
axios.create.mockImplementation(()=>({get}))
const apiclient = new ApiClient.AsyncClient(BASE_URL);
await apiclient.get("something")
expect(get).toHaveBeenCalledTimes(1);
});
关于javascript - 如何使用 Jest 模拟构造函数状态初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55188024/