jest promises code example

Example 1: jest async test fetch api

// fetch.js
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()
  }
}


// fetch.test.js
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) {
      // have to manually handle the failed test with "done.fail"
      done.fail(e)
    }
  })

Tags:

Css Example