toThrowError

Bun

Symbol

Matchers.toThrowError

toThrowError(expected?: unknown): void

Asserts that a function throws an error.

  • If expected is a string or RegExp, it will check the message property.
  • If expected is an Error object, it will check the name and message properties.
  • If expected is an Error constructor, it will check the class of the Error.
  • If expected is not provided, it will check if anything has 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();