node.js - 如何使用 jest-mock-axios 来测试调用 axios.get 的函数?
问题描述
我写了一个我正在尝试测试的函数。我在https://www.npmjs.com/package/jest-mock-axios#user-content-using-await-and-async上遵循了一个示例。结构上唯一的主要区别是我使用的是 axios.get 而不是 axios.post。当我运行测试时,输出是这样的:
这是我编写的要进行单元测试的函数:
const axios = require("axios");
async function getConnectionFromApiKey(apiKey, apiKeyUri) {
const res = await axios.get(apiKeyUri, {
headers: { "x-hs-apikey": apiKey },
params: { "applicationGuid": '' }
});
const connectionString = res.data.result[0].result.var_value;
return buildDbConnectionConfig(connectionString, 'xxxx');
}
function buildDbConnectionConfig(connectionString, domainToCheck) {
// returns an mssql config object
return {
....
}
}
这是测试代码:
const mockAxios = require('jest-mock-axios').default; // why does it seem i have to reference the default object?
const apiKeyValidator = require('../apikey');
require("jest-json");
const apiKey = 'abc123';
const apiKeyUrl = '/VerifyAPIKey/';
const expectedCxn = {
// mssql connection object properties
};
it('should return a database connection object', async () => {
const promise = apiKeyValidator.getConnectionFromApiKey(apiKey, apiKeyUrl);
expect(mockAxios.get).toHaveBeenCalledWith(apiKeyUrl, {
headers: { "x-hs-apikey": apiKey },
params: { "applicationGuid": "" }
});
// simulating a server response
const responseObj = {
// resonseObj properties
};
mockAxios.mockResponse(responseObj);
const result = await promise;
expect(result).toMatchJSON(expectedCxn);
});
#更新
我忽略了描述创建 axios 模拟的文档部分。所以我的下一个问题是如何使用 jest.fn() 来设置模拟函数。我尝试了 mockAxios.get = jest.fn() 但这似乎没有奏效。我错过了什么?
解决方案
推荐阅读
- java - 如何使用java访问桥获取JTable中的单元格
- react-native - 世博会视频重新渲染状态变化
- html - 'FILE' 输入在第二次尝试后不保留第一个选定元素(多个文件上传)
- python - 使用索引查找矩阵的边缘
- jmeter - 如何使用 JMeter 基于 Keycloak 测试测试登录?
- python - 尝试使用 pyinstaller 制作烧瓶应用程序的独立可执行文件
- java - 使用 Spring Boot 进行 Cucumber 集成测试
- r - R:“添加”2 个变量(列)来创建一个聚合变量(列)?
- php - Jquery单选按钮值不变
- python - 获取与类名匹配的所有元素