mock a promise in jest code example
Example: jest async test fetch api
async function fetchUser() {
const url = 'https://jsonplaceholder.typicode.com/users'
const response = await fetch(url)
return await response.json()
}
const fetchPosts = {
async postAPI() {
const url = 'https://jsonplaceholder.typicode.com/posts'
const response = await fetch(url)
return await response.json()
}
}
test('async fetch action users', async (done) => {
const response = await fetchUser()
expect(response.length).toBe(10);
done()
});
test('async fetch action posts using Jetst Spy', async (done) => {
const spyOn = jest.spyOn(fetchPosts, 'postAPI')
const response = await fetchPosts.postAPI()
expect(spyOn).toHaveBeenCalled()
expect(response.length).toBe(100);
done()
})