【发布时间】:2021-09-10 18:35:06
【问题描述】:
我正在努力执行一个关于 axios api 调用的测试
这是我的 API 调用,它在我的程序中完美运行
import axios from 'axios';
import crypto from 'crypto';
import { prop } from 'ramda';
const baseUrl = 'http://gateway.marvel.com:80';
const uri = '/v1/public/characters';
const charactersUrl = baseUrl + uri;
const timestamp = [Math.round(+new Date() / 1000)];
const privateApi = 'XXX';
const publicApi = 'XXX';
const concatenatedString = timestamp.concat(privateApi, publicApi).join('');
const hash = crypto.createHash('md5').update(`${concatenatedString}`).digest('hex');
const charactersApi = () =>
axios
.get(charactersUrl, {
params: {
ts: timestamp,
apikey: publicApi,
hash,
},
})
.then(prop('data'));
export default charactersApi;
当我尝试测试它时,这样:
import axiosMock from 'axios';
import charactersApi from '../marvelApi';
jest.mock('axios', () => ({
get: jest.fn(),
}));
describe('tools | marvelApi', () => {
const piece = { name: '3D-MAN' };
axiosMock.get.mockResolvedValueOnce({ data: piece });
it('should get the character', () => {
return charactersApi().then(elem => {
expect(elem.name).toEqual('3D-MAN');
});
});
});
我从 jest 收到以下消息
TypeError: Cannot read property 'then' of undefined
16 |
17 | const charactersApi = () =>
> 18 | axios
| ^
19 | .get(charactersUrl, {
20 | params: {
21 | ts: timestamp,
at charactersApi (src/tools/marvelApi.js:18:3)
at Object.<anonymous> (src/tools/tests/marvelApi.test.js:13:12)
我的尝试
- 一个常见的错误是忘记了包含请求 API 的函数中的 return 语句,在我的例子中它是正确完成的(第一段代码 -> charactersApi())source1,source2
- 我还尝试从模拟的 Axios 返回一个 Promise,正如我在另一张 SO 票证上看到的那样
jest.mock('axios', () => ({
get: jest.fn(() => Promise.resolve()),
}));
我认为我的 axios mock 不正确,因为斗争来自测试,而生产版本运行良好
有什么想法吗?
【问题讨论】:
-
永远不要暴露你的 api 密钥!我已经为你删除了。
-
谢谢,一开始我已经部分去掉了私钥,我觉得够了