Challenge your understanding of asynchronous testing in Jest with focused questions on async functions, promises, and async testing methods. This quiz evaluates key concepts that are vital for writing effective asynchronous tests in modern JavaScript projects.
Which method is recommended to test an async function that returns a promise in Jest?
Explanation: Returning the promise from the test function ensures that Jest knows when the asynchronous operation is finished. Placing setTimeout in a describe block does not control test timing. Using expect.assertTrue is syntactically incorrect; expect should be used. Omitting the return statement may cause tests to pass before the promise is resolved or rejected.
When testing that an async function throws or rejects, which Jest matcher is most appropriate to use with async/await?
Explanation: The correct way to assert that a promise rejects with an error is using await expect(promise).rejects.toThrow(). toThrowSync() is not a valid Jest matcher and applies to synchronous code. throwsAsync() is similarly invalid. resolves.toThrow() is incorrect because toThrow is for errors thrown, not resolved values.
In which scenario should you use the done callback in Jest tests for async code?
Explanation: The done callback is used when testing asynchronous code that uses callbacks instead of promises, allowing you to signal when the test is complete. For promise-based or async/await code, you should not use done. Using done is unnecessary for synchronous code and will not help Jest handle timeouts automatically.
If you need to test that multiple async operations (promises) resolve as expected in a single Jest test, what is the best approach?
Explanation: Using Promise.all and returning or awaiting the combined result ensures that all async operations are completed before the test ends. Nesting operations in separate it blocks splits them into separate tests. Calling expect without awaiting risks the test finishing before the assertions run. describe is for grouping tests, not for handling async logic.
Which method helps simulate or control setTimeout and setInterval in Jest async tests?
Explanation: jest.useFakeTimers() allows you to simulate and manage timer functions, making it easier to test timing-dependent async code. Wrapping timers in promises does not control their execution. setImmediate is a separate method, not a replacement for setTimeout. There's no jest.timeout() method to change test timeout.