0xa*_*mal 1 javascript unit-testing node.js jestjs axios
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 = new ApiClient.AsyncClient(BASE_URL);
// TypeError: Cannot read property `get` of undefined
return await apiclient.get("something").then(response => {
expect(axios.get).toHaveBeenCalledTimes(1);
});
});
Run Code Online (Sandbox Code Playgroud)
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));
}
}
};
Run Code Online (Sandbox Code Playgroud)
您需要进行模拟,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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
654 次 |
| 最近记录: |