我正在尝试使用github
测试对api
jest
的呼叫,以查看是否返回了结果(目的是测试我的单元测试技能)。但是由于某些原因,我的代码可以正常运行,但仍然无法通过测试。我怀疑我很可能不了解如何编写这类测试。下面是我的代码
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;
});
}
}
上面的代码以array
格式返回正确的结果,但下面的test
失败
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'])
})
});
});
请问此test
有什么问题,我该如何解决?
答案 0 :(得分:1)
需要修复两件事。
您需要从函数中返回result
。可以简化为:
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;
});
}
}
...使response
成为数组,因此直接对其进行测试:
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'
的新仓库,我将其添加到期望值)。