'Jest Mock issues with async functions with .then
i have the follow code
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}`)
})
}
With this Jest Test
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")
});
});
and here is where i have the issue the follow output from running yarn test
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)
when i remove the .then() and reduce the complexity of the async function works the jest test, but i need the code to stay like this, i suppose there are some error or conflict when i pass the first .then() but i do not know how to solve.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
