简体   繁体   中英

Why "return" on a promise-based test with Jest?

This is a Jest test example:

test("Asynchronous code", () => {
    return Promise.resolve("data").then(res => {
        expect(res).toBe("data");
    });
});

Docs for Jest indicate that we have to return a Promise in a test, because without return :

Your test will complete before the promise returned [...] and then() has a chance to execute the callback.

So if I don't return , expect(res).toBe("data") will never be executed.

But I tested, and it worked the same with or without return (with .resolves and .rejects as well).

To be sure, I write a test without return supposed to failed:

test("Asynchronous code", () => {
    Promise.resolve("data").then(res => {
        expect(res).toBe("a failure");
    });
});
  • If expect(res).toBe("data") is never executed, the test will pass: return is required.
  • If the assertion is well tested, the test failed: what do we need return for?
 FAIL  Cours-Jest/--test--/test.js
  ● Asynchronous code

    expect(received).toBe(expected) // Object.is equality

    Expected: "a failure"
    Received: "data"

So the assertion is correctly executed. Why do we have to return ? What am I missing?

From the doc:

Return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will fail.

So when you do something asynchronously and don't return the promise, two things can go wrong:

  1. So when your promise actually does something asynchronously that takes longer than the test timeout... your .then() will not fire at all. There may even be no timeout, as your tests returns immediately.
  2. When your promise is rejected, the error is ignored.

A better way to test promises:

test("Asynchronous code", async () => {
    const res = await Promise.resolve("data");
    expect(res).toBe("data");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM