.rejects

Use .rejects to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails.

For example, this code tests that the promise rejects with reason 'octopus':

  1. test('rejects to octopus', () => {
  2. // make sure to add a return statement
  3. return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
  4. 'octopus',
  5. );
  6. });

Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to tell Jest to wait by returning the unwrapped assertion.

Alternatively, you can use async/await in combination with .rejects.

  1. test('rejects to octopus', async () => {
  2. await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
  3. });