Explore essential concepts for handling errors and exceptions in Jest test cases with this quiz. Assess your understanding of asynchronous failures, thrown errors, promise rejection handling, and best practices for ensuring reliable test results.
When testing a function that throws an error synchronously, which Jest matcher should you use to ensure the error is thrown as expected?
Explanation: The toThrow matcher is used in Jest to check whether a function throws an error when invoked, making it the correct choice for synchronous errors. The option toBeThrown is incorrect, as there is no such matcher in Jest. The option toRaise and toError are also not valid Jest matchers. Only toThrow will properly assert synchronous error-throwing behavior.
Suppose you are testing an asynchronous function that returns a rejected promise. Which Jest matcher should be used to check for the rejection in this scenario?
Explanation: The matcher rejects.toThrow is specifically meant for asserting that a promise is rejected with a thrown error. The option resolves.toThrow is incorrect because it checks resolution, not rejection. There is no toReject or throwAsync matcher natively in Jest, making them invalid choices. Only rejects.toThrow accurately verifies rejected promise errors.
In a Jest test for async code, what is a necessary step to ensure the test fails if an error is not thrown as expected?
Explanation: You must return the promise or use async/await to let Jest know to wait for asynchronous completion; otherwise, the test may end before the error is caught, resulting in false positives. Setting the timeout to zero disrupts test execution rather than improving error capture. Making assertions outside the promise can cause missed failures. Only observing console.error does not let the test fail automatically.
If you use .catch to handle a rejected promise in a Jest test, but do not include an assertion inside the .catch block, what is the likely test result?
Explanation: Without an assertion in the .catch block, the test may pass even when an error is thrown, because Jest has no way to know that the rejection was unexpected. Jest does not automatically fail tests just because .catch is invoked, nor does it throw a syntax warning or skip the test. Proper assertions within .catch blocks are essential to correctly capture failures.
Which approach best ensures your Jest test verifies that an error was both thrown and has the expected message?
Explanation: Using toThrow with a specific error message lets your test confirm that not only was an error thrown but that it matches the expected message or pattern. Checking only if the error is truthy does not verify message details. Printing the error provides no verification. Catching and ignoring the error could hide test failures, making them poor choices.