Deepen your understanding of how to effectively test Promises and async/await patterns in Jest. This quiz covers best practices, common pitfalls, and practical scenarios in asynchronous JavaScript testing using Jest’s features.
Which approach correctly tests a function that returns a Promise resolving to a value in Jest?
Explanation: Returning the Promise from the test function ensures Jest waits for it to settle before finishing the test, making it the correct approach. Simply calling the function and asserting outside of .then can result in false positives as the assertion may run before resolution. setTimeout introduces unreliable timing and is not recommended for asynchronous testing. While try-catch is useful for async/await, it does not itself make Jest wait for Promises returned by the test.
What is the correct way to test an async function in Jest for a resolved value?
Explanation: Declaring the test as async and using await allows Jest to handle asynchronous code neatly, waiting for completion before assertions. Using expect without await will not ensure the function has finished execution. Callback-based done is more suitable for older callback patterns, not for async/await functions. Relying on implicit resolution risks timing issues and unclear test outcomes.
Given an async function that rejects, how should you assert it throws the expected error in Jest?
Explanation: The correct way is to use await expect(promise).rejects.toThrow(error), which verifies the Promise rejects with a specific error. Using expect(promise).toThrow(error) is incorrect since toThrow expects a sync error, not a rejected Promise. The then success callback will not capture the rejection. Awaiting the promise and catching the error manually works but is verbose and less integrated with Jest’s assertion utilities.
How can you properly test that an async function resolves to 'done' in Jest?
Explanation: Using await expect with resolves ensures Jest waits for the Promise to resolve and checks the value. Calling expect directly without awaits will produce a Promise instead of the intended result. Ignoring the resolved value with a done callback misses the value assertion. Using setTimeout is unreliable and makes the test less deterministic.
What must you do when testing Promises in functions that use setTimeout with Jest’s mocked timers?
Explanation: Manually advancing timers using jest.runAllTimers or jest.advanceTimersByTime triggers Promise resolutions scheduled by setTimeout, ensuring proper execution in tests. Relying on Jest to detect Promise resolution without advancing timers will leave scheduled callbacks pending. Resetting modules is unrelated to timer handling. Avoiding async/await with mocked timers is unnecessary and limits test clarity.