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.

Callbacks

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 just the string 'peanut butter'.

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

  1. // Don't do this!
  2. test('the data is peanut butter', () => {
  3. function callback(data) {
  4. expect(data).toBe('peanut butter');
  5. }
  6. fetchData(callback);
  7. });

The problem is that the test will complete as soon as fetchData completes, before ever calling the callback.

There is an alternate form of test that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called done. Jest will wait until the done callback is called before finishing the test.

  1. test('the data is peanut butter', done => {
  2. function callback(data) {
  3. expect(data).toBe('peanut butter');
  4. done();
  5. }
  6. fetchData(callback);
  7. });

If done() is never called, the test will fail, which is what you want to happen.

Promises

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.

For example, let's say that fetchData, instead of using a callback, returns a promise that is supposed to resolve to the string 'peanut butter'. We could test it with:

  1. test('the data is peanut butter', () => {
  2. return fetchData().then(data => {
  3. expect(data).toBe('peanut butter');
  4. });
  5. });

Be sure to return the promise - if you omit this return statement, your test will complete before the promise returned from fetchData resolves and then() has a chance to execute the callback.

If you expect a promise to be rejected use the .catch method. Make sure to add expect.assertions to verify that a certain number of assertions are called. Otherwise a fulfilled promise would not fail the test.

  1. test('the fetch fails with an error', () => {
  2. expect.assertions(1);
  3. return fetchData().catch(e => expect(e).toMatch('error'));
  4. });

.resolves / .rejects

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.

  1. test('the data is peanut butter', () => {
  2. return expect(fetchData()).resolves.toBe('peanut butter');
  3. });

Be sure to return the assertion—if you omit this return statement, your test will complete before the promise returned from fetchData is resolved and then() has a chance to execute the callback.

If you expect a promise to be rejected use the .rejects matcher. It works analogically to the .resolves matcher. If the promise is fulfilled, the test will automatically fail.

  1. test('the fetch fails with an error', () => {
  2. return expect(fetchData()).rejects.toMatch('error');
  3. });

Async/Await

Alternatively, you can use async and await in your tests. To write an async test, just use the async keyword in front of the function passed to test. For example, the same fetchData scenario can be tested with:

  1. test('the data is peanut butter', async () => {
  2. expect.assertions(1);
  3. const data = await fetchData();
  4. expect(data).toBe('peanut butter');
  5. });
  6. test('the fetch fails with an error', async () => {
  7. expect.assertions(1);
  8. try {
  9. await fetchData();
  10. } catch (e) {
  11. expect(e).toMatch('error');
  12. }
  13. });

Of course, you can combine async and await with .resolves or .rejects.

  1. test('the data is peanut butter', async () => {
  2. await expect(fetchData()).resolves.toBe('peanut butter');
  3. });
  4. test('the fetch fails with an error', async () => {
  5. await expect(fetchData()).rejects.toThrow('error');
  6. });

In these cases, 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 simpler.

原文: https://jestjs.io/docs/en/asynchronous