Best Way to Test Promises in Jest

Asked
Active3 hr before
Viewed126 times

6 Answers

promises
90%

Meta Stack Overflow ,Stack Overflow en español, Stack Overflow Public questions & answers , Stack Overflow help chat

Nowadays you can write it in this way as well: docs

describe('Fetching', () => {
   const filters = {
      startDate: '2015-09-01'
   };
   const api = new TestApiTransport();

   it('should reject if no startdate is given', () => {
      expect.assertions(1);
      return expect(MyService.fetch()).rejects.toEqual({
         error: 'Your code message',
      });
   });

   it('should return expected data', () => {
      expect.assertions(1);
      return expect(MyService.fetch(filters, null, api)).resolves.toEqual(extectedObjectFromApi);
   });
});
load more v
88%

Testing Asynchronous Code,If your code uses promises, there is a more straightforward way to handle asynchronous tests. Return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail.,It's common in JavaScript for code to run asynchronously. When you have code that runs asynchronously, Jest needs to know when the code it is testing has completed, before it can move on to another test. Jest has several ways to handle this.,You can also use the .resolves matcher in your expect statement, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail.

The most common asynchronous pattern is callbacks.

For example, let's say that you have a fetchData(callback) function that fetches some data and calls callback(data) when it is complete. You want to test that this returned data is the string 'peanut butter'.

fetchData(callback)

The most common asynchronous pattern is callbacks.

For example, let's say that you have a fetchData(callback) function that fetches some data and calls callback(data) when it is complete. You want to test that this returned data is the string 'peanut butter'.

callback(data)

The most common asynchronous pattern is callbacks.

For example, let's say that you have a fetchData(callback) function that fetches some data and calls callback(data) when it is complete. You want to test that this returned data is the string 'peanut butter'.

'peanut butter'
load more v
72%

Since the test function defines the done parameter, Jest will wait for expectations until done() is invoked. Jest, by default, will wait for up to five seconds for a test to complete. Otherwise, the test will fail.,For callback-based code, Jest provides a done callback as the argument of the test function. We should invoke this function after we are done asserting.,Jest typically expects to execute the tests’ functions synchronously. If we do an asynchronous operation, but we don't let Jest know that it should wait for the test to end, it will give a false positive.,We need to inform Jest that it should wait until the assertions run. How we do this depends on which asynchronous patterns the code we want to test uses.

1 test("this shouldn't pass", () => {
   2 setTimeout(() => {
      3 // this should fail:
      4 expect(false).toBe(true);
      5
   });
   6
});
load more v
65%

If your code uses promises, there is a simpler way to handle asynchronous tests. Just return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail.,Be sure to return the promise - if you omit this return statement, your test will complete before fetchData completes.,In this case, async and await are effectively just syntactic sugar for the same logic as the promises example uses.,None of these forms is particularly superior to the others, and you can mix and match them across a codebase or even in a single file. It just depends on which style makes your tests the simplest.

By default, Jest tests complete once they reach the end of their execution. That means this test will not work as intended:

// Don't do this!
test('the data is peanut butter', () => {
   function callback(data) {
      expect(data).toBe('peanut butter');
   }

   fetchData(callback);
});
load more v
75%

The async methods return Promises, so be sure to use await or .then when calling them.,Here is an example where the promise resolves because the element is removed:,This can be useful if you have a unit test that mocks API calls and you need to wait for your mock promises to all resolve.,findBy methods are a combination of getBy queries and waitFor. They accept the waitFor options as the last argument (e.g. await screen.findByText('text', queryOptions, waitForOptions)).

Several utilities are provided for dealing with asynchronous code. These can be useful to wait for an element to appear or disappear in response to an event, user action, timeout, or Promise. (See the guide to testing disappearance.)

The async methods return Promises, so be sure to use await or .then when calling them.

await

Several utilities are provided for dealing with asynchronous code. These can be useful to wait for an element to appear or disappear in response to an event, user action, timeout, or Promise. (See the guide to testing disappearance.)

The async methods return Promises, so be sure to use await or .then when calling them.

.then
load more v
40%

If your code makes use promises, a simpler way to handle asynchronous tests exists. All you need to do is to return a promise from your test, and Jest waits for that promise to resolve. In the case where the promise is rejected, the test automatically fails.,In such cases, async and await are just syntactic sugar for the same logic as the promises example uses.,None of these forms can be said to superior to the others, and you can mix and match them across your codebase or even within a single file. It only depends on which style makes your tests simpler.,The problem in the code above is that the test completes as soon as fetchData completes, before the callback is ever called.

By default, Jest tests will complete once they reach the end of their execution. That means that the test below will not work as intended:

// Do not do this!
test('the data will be peanut butter', () => {
   function callback(data) {
      expect(data).toBe('peanut butter');
   }

   fetchData(callback);
});
load more v

Other "promises-undefined" queries related to "Best Way to Test Promises in Jest"