jest await all async code example
Example 1: 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()
})
Example 2: jest always pass async await
test.only("should not pass", async (done) => {
try {
const a = await getAsync()
expect(a).toEqual(2)
done()
} catch (e) {
done.fail(e)
}
})