对node.js来说是新手。我正在编写一个JS客户机,它封装了底层的axios库。在单元测试中,我使用取笑模拟axios。
在我的API类的构造函数中,我传递一个URL,并使用axios.create函数创建axios的自定义实例,并将其绑定到客户端属性。
当我用jest.mock('axios')来模拟axios依赖关系时,问题就出现了--当尝试调用axios.get时,在测试中抛出了一个TypeError。
TypeError: Cannot read property `get` of undefined我理解为什么会发生这种情况,但我还没有找到一种方法来使我能够模拟axios,并且不需要对客户端字段进行未定义。除了通过构造函数注入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));
}
}
};发布于 2019-03-15 19:30:03
您需要模拟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);
});https://stackoverflow.com/questions/55188024
复制相似问题