【发布时间】:2022-11-11 03:55:57
【问题描述】:
我正在尝试使用 jest 为 axios 发布请求编写单元测试。 这是我的实际功能-
exports.getAccessToken = function (urlToCall, scope, basicAuthToken) {
return new Promise(function (resolve, reject) {
let axios = require("axios");
let qs = require("qs");
let data = qs.stringify({
grant_type: "client_credentials",
scope: scope,
});
let config = {
method: "post",
url: urlToCall,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Basic " + basicAuthToken,
},
data: data,
};
axios(config)
.then(function (response) {
resolve(response.data);
})
.catch(function (error) {
console.log(
"error occurred while getting access token for the scope - ",
scope,
" and the error is - ",
error
);
});
});
};
这是我的单元测试代码 -
const processUtils = require('../src/utils/process-utils')
const axios = require('axios')
jest.mock("axios")
describe("when getAccessToken API is successful", () => {
test('should return access token', async () => {
const expectedResponse = JSON.stringify({
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImMxZDY2OTF",
"issued_token_type": "token-type:access_token",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "consumer_profile:read:"
})
axios.post.mockResolvedValueOnce(() => Promise.resolve(expectedResponse))
// axios.post.mockImplementationOnce(() => Promise.resolve(expectedResponse));
let urlToCall = 'https://somehost.com/access_token/v1'
let scope = jest.fn
let basicAuthToken = jest.fn
const response = await processUtils.getAccessToken(urlToCall, scope, basicAuthToken)
expect(mockAxios.post).toHaveBeenCalledWith(urlToCall)
expect(response).toEqual(expectedResponse)
});
});
这是运行 jest 时抛出的错误 -
TypeError: Cannot read properties of undefined (reading 'then')
> axios(config)
.then(function (response) {
resolve(response.data);
})
https://i.stack.imgur.com/NZiVp.png 我是节点和笑话的新手。有人可以指出我在这里缺少什么吗?
【问题讨论】:
-
在导出函数中包含
requires 是很不寻常的,我不确定它的行为方式。您是否尝试将它们放在exports之外?