Course contentsShow
← JavaScript
Lesson 2688 of 2,72354. Testing in JavaScriptFree lesson

Testing Promise Rejections

Asserting that a promise rejects with expect().rejects or try/catch patterns.

Testing Promise Rejections

You'll learn how to properly assert that a promise rejects with the expected error in your tests.

When testing code that's supposed to fail—like validation functions, error-throwing APIs, or network calls to bad endpoints—you need to verify that the rejection happens correctly. Just like you test success paths, you must test failure paths to ensure your error handling works as intended.

Using expect().rejects (Jest/Vitest)

Most modern test runners provide a .rejects matcher that works seamlessly with promises:

test('should reject with an error when input is invalid', async () => {
  await expect(fetchUser(-1)).rejects.toThrow('Invalid user ID');
});

This reads naturally: "expect this promise to reject, and match the thrown error." You can chain any matcher after .rejects, like toThrow(), toMatch(), or toEqual().

The Try/Catch Pattern

Alternatively, use async/await with try/catch to manually verify the rejection:

test('should reject with specific error message', async () => {
  try {
    await fetchUser(-1);
    // If we reach here, the test should fail
    throw new Error('Expected promise to reject');
  } catch (error) {
    expect(error.message).toBe('Invalid user ID');
  }
});

Notice the guard statement: if the promise doesn't reject, you throw a manual error to fail the test. Otherwise, a false positive might slip through.

Which Approach to Use?

The .rejects matcher is cleaner and less boilerplate. Use try/catch when you need fine-grained control over the caught error or when testing multiple properties of the rejection.

Key Takeaway: Always test promise rejections using either expect().rejects or an explicit try/catch block with a guard statement—never leave rejection assertions untested, as silent failures create dangerous blind spots in your test coverage.