首页 > 解决方案 > 如何使用 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() 但这似乎没有奏效。我错过了什么?

标签: node.jsjestjsaxiosjest-mock-axios

解决方案


推荐阅读