method

test.MatchersBuiltin.toThrowError

expected?: unknown
): void;

Asserts that a function throws an error.

  • If expected is a string or RegExp, it checks the message property.
  • If expected is an Error object, it checks the name and message properties.
  • If expected is an Error constructor, it checks the class of the Error.
  • If expected is not provided, it checks that anything was thrown.
@param expected

the expected error, error message, or error pattern

function fail() {
  throw new Error("Oops!");
}
expect(fail).toThrowError("Oops!");
expect(fail).toThrowError(/oops/i);
expect(fail).toThrowError(Error);
expect(fail).toThrowError();