method

test.Matchers.toThrow

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).toThrow("Oops!");
expect(fail).toThrow(/oops/i);
expect(fail).toThrow(Error);
expect(fail).toThrow();