我正在尝试使用 jest
测试对 github
api
的调用,看看是否返回结果(这样做的目的是测试我的单元测试技能)。但由于某些原因,我的代码工作正常,但仍然未通过测试。我怀疑我很可能不明白如何编写此类测试。下面是我的代码
const functions = {
getUserRepo: async (username) => {
const url = `https://api.github.com/users/${username}/repos`;
console.log(url);
let result = [];
await axios.get(url)
.then(function (response) {
response.data.forEach(value => result.push(value.name));
return result;
})
.catch(function (error) {
return error;
});
}
}
上面的代码以数组
格式返回正确的结果,但下面的测试
失败
describe('Check repos from git api', () => {
test('Should return user repos', async () => {
await functions.getUserRepo('whitehox')
.then((response) => {
expect(response.data).toEqual([ '57','decafreelance','decases','eexport','exportchat','flisch', 'gitprac', 'itravelcentral', 'pollark', 'portfolio', 'startereit', 'talkative', 'team-portfolio'])
})
});
});
请问此测试
有什么问题以及如何修复它?
最佳答案
有两件事需要修复。
您需要从函数返回结果
。可以简化为:
const functions = {
getUserRepo: (username) => {
const url = `https://api.github.com/users/${username}/repos`;
console.log(url);
return axios.get(url) // <= return the result
.then(function (response) {
return response.data.map(value => value.name);
})
.catch(function (error) {
return error;
});
}
}
...这使得响应
数组,因此可以直接测试它:
describe('Check repos from git api', () => {
test('Should return user repos', async () => {
await functions.getUserRepo('whitehox')
.then(response => {
// response **is** the array
expect(response).toEqual(['57', 'decafreelance', 'decases', 'eexport', 'exportchat', 'flisch', 'gitprac', 'itravelcentral', 'pollark', 'portfolio', 'startereit', 'talkative', 'team-portfolio', 'YorubaIndigenous']); // Success!
})
});
});
(...还有一个名为 'YorubaIndigenous'
的新存储库,我将其添加到预期值中)。
关于javascript - 使用 jest 测试 Javascript 对 api 的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55603838/