jestjs/jest · error · Error

expected value must be a string or regular expression or cla

Error message

expected value must be a string or regular expression or class or error

What it means

Thrown by `toThrow` / `toThrowError` (toThrowMatchers.ts:78, via `createMatcher`) when the `expected` argument does not match any of the accepted shapes: string (substring), function (error class), object with `.test` (RegExp), object with `.asymmetricMatch` (asymmetric matcher like `expect.any(Error)`), or plain object (Error shape). The matcher dispatches on `typeof` and duck-typed properties; reaching the final `else` branch means none of them matched — typically a primitive like a number, boolean, undefined-with-explicit-passing, or a malformed object.

Source

Thrown at packages/expect/src/toThrowMatchers.ts:129

    }

    if (expected === undefined) {
      return toThrow(matcherName, options, thrown);
    } else if (typeof expected === 'function') {
      return toThrowExpectedClass(matcherName, options, thrown, expected);
    } else if (typeof expected === 'string') {
      return toThrowExpectedString(matcherName, options, thrown, expected);
    } else if (expected !== null && typeof expected.test === 'function') {
      return toThrowExpectedRegExp(matcherName, options, thrown, expected);
    } else if (
      expected !== null &&
      typeof expected.asymmetricMatch === 'function'
    ) {
      return toThrowExpectedAsymmetric(matcherName, options, thrown, expected);
    } else if (expected !== null && typeof expected === 'object') {
      return toThrowExpectedObject(matcherName, options, thrown, expected);
    } else {
      throw new Error(
        matcherErrorMessage(
          matcherHint(matcherName, undefined, undefined, options),
          `${EXPECTED_COLOR(
            'expected',
          )} value must be a string or regular expression or class or error`,
          printWithType('Expected', expected, printExpected),
        ),
      );
    }
  };

const matchers: MatchersObject = {
  toThrow: createMatcher('toThrow'),
};

const toThrowExpectedRegExp = (
  matcherName: string,
  options: MatcherHintOptions,

View on GitHub (pinned to f49721c78e)

Solutions

  1. If checking the message, pass a string: `.toThrow('Not found')`.
  2. If checking the class, pass the constructor: `.toThrow(NotFoundError)`.
  3. If checking a pattern, pass a RegExp: `.toThrow(/not found/i)`.
  4. If checking the shape, pass an Error-like plain object: `.toThrow({message: 'x'})`, or use `expect.any(Error)` for asymmetric matching.

Example fix

// before
expect(() => fetch()).toThrow(404); // number is not a valid expected

// after
expect(() => fetch()).toThrow(NotFoundError); // error class
Defensive patterns

Strategy: type-guard

Validate before calling

const valid =
  typeof expected === 'string' ||
  typeof expected === 'function' ||
  (expected instanceof RegExp) ||
  (expected instanceof Error) ||
  (expected != null && typeof expected === 'object');
if (!valid) {
  throw new Error(`expected must be string/regex/class/error/object, got ${typeof expected}`);
}
expect(fn).toThrow(expected);

Type guard

type ToThrowExpected = string | RegExp | (new (...args: any[]) => Error) | Error | object;
const isToThrowExpected = (v: unknown): v is ToThrowExpected =>
  typeof v === 'string' ||
  typeof v === 'function' ||
  v instanceof RegExp ||
  v instanceof Error ||
  (v != null && typeof v === 'object');

Try / catch

try {
  expect(fn).toThrow(expected);
} catch (e) {
  if (e instanceof Error && /must be a string or regular expression or class or error/.test(e.message)) {
    console.error('expected was an unsupported type:', typeof expected, expected);
  }
  throw e;
}

Prevention

When it happens

Trigger: Calling `expect(fn).toThrow(404)` (number status code), `.toThrow(true)`, `.toThrow(['err'])` (array), `.toThrow(null)`, or `.toThrow(new Error('x'))` where you intended to pass the class (`Error`) or the message string (`'x'`) instead of an instance. Note: passing an `Error` instance is dispatched to `toThrowExpectedObject` (instanceof Error is an object) — so this error specifically means a non-Error primitive or a non-class function returning a non-Error.

Common situations: Passing a numeric status code instead of an error message or class; passing an error instance where the class was intended (`new Error()` vs `Error`); passing a boolean flag by mistake; mis-importing a constant as undefined; refactor that changed the expected from string to number.

Related errors


AI-assisted analysis of jestjs/jest@f49721c78e (2026-08-03). Data as JSON: /data/errors/a842c7c237d49872.json. Report an issue: GitHub.