我有以下代码
async function searchCharacter(){
const response = await fetch("https://rickandmortyapi.com/api/character/?name=")
.then((response) => {
if(response.status !== 200) throw `HTTP error: ${response.status}`;
const data = response.json();
return data
})
.then( (body) => {
const [first] = body.results;
console.log(first)
})
.catch( (error) => {
console.log(`Error: ${error}`)
})
}
有了这个笑话测试
describe('searchCharacter', () => {
it('gets the character data', async () => {
const responses = {
status: "200",
json() => {return {name: "ricky"}}
}
fetch.mockResolvedValueOnce(responses);
const char = await searchCharacter();
expect(char.name).toBe("ricky")
});
});
这就是我遇到运行纱线测试的后续输出的问题
TypeError: Cannot read property 'name' of undefined
32 |
33 | const char = await searchCharacter();
> 34 | expect(char.name).toBe("ricky")
| ^
35 |
36 | });
37 | /*
at Object.<anonymous> (tests/searchCharacter.test.js:34:17)
当我删除 .then() 并降低异步函数的复杂性时,这是开玩笑的测试,但我需要代码保持这样,我想当我通过第一个 .then() 时会出现一些错误或冲突,但我不知道怎么解决。