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:returnis required. - If the assertion is well tested, the test failed: what do we need
returnfor?
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?