{"id":"a842c7c237d49872","repo":"jestjs/jest","slug":"expected-value-must-be-a-string-or-regular-express-a842c7","errorCode":null,"errorMessage":"expected value must be a string or regular expression or class or error","messagePattern":"expected value must be a string or regular expression or class or error","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/expect/src/toThrowMatchers.ts","lineNumber":129,"sourceCode":"    }\n\n    if (expected === undefined) {\n      return toThrow(matcherName, options, thrown);\n    } else if (typeof expected === 'function') {\n      return toThrowExpectedClass(matcherName, options, thrown, expected);\n    } else if (typeof expected === 'string') {\n      return toThrowExpectedString(matcherName, options, thrown, expected);\n    } else if (expected !== null && typeof expected.test === 'function') {\n      return toThrowExpectedRegExp(matcherName, options, thrown, expected);\n    } else if (\n      expected !== null &&\n      typeof expected.asymmetricMatch === 'function'\n    ) {\n      return toThrowExpectedAsymmetric(matcherName, options, thrown, expected);\n    } else if (expected !== null && typeof expected === 'object') {\n      return toThrowExpectedObject(matcherName, options, thrown, expected);\n    } else {\n      throw new Error(\n        matcherErrorMessage(\n          matcherHint(matcherName, undefined, undefined, options),\n          `${EXPECTED_COLOR(\n            'expected',\n          )} value must be a string or regular expression or class or error`,\n          printWithType('Expected', expected, printExpected),\n        ),\n      );\n    }\n  };\n\nconst matchers: MatchersObject = {\n  toThrow: createMatcher('toThrow'),\n};\n\nconst toThrowExpectedRegExp = (\n  matcherName: string,\n  options: MatcherHintOptions,","sourceCodeStart":111,"sourceCodeEnd":147,"githubUrl":"https://github.com/jestjs/jest/blob/f49721c78e195558b40913977c9230f5b7f559d8/packages/expect/src/toThrowMatchers.ts#L111-L147","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["If checking the message, pass a string: `.toThrow('Not found')`.","If checking the class, pass the constructor: `.toThrow(NotFoundError)`.","If checking a pattern, pass a RegExp: `.toThrow(/not found/i)`.","If checking the shape, pass an Error-like plain object: `.toThrow({message: 'x'})`, or use `expect.any(Error)` for asymmetric matching."],"exampleFix":"// before\nexpect(() => fetch()).toThrow(404); // number is not a valid expected\n\n// after\nexpect(() => fetch()).toThrow(NotFoundError); // error class","handlingStrategy":"type-guard","validationCode":"const valid =\n  typeof expected === 'string' ||\n  typeof expected === 'function' ||\n  (expected instanceof RegExp) ||\n  (expected instanceof Error) ||\n  (expected != null && typeof expected === 'object');\nif (!valid) {\n  throw new Error(`expected must be string/regex/class/error/object, got ${typeof expected}`);\n}\nexpect(fn).toThrow(expected);","typeGuard":"type ToThrowExpected = string | RegExp | (new (...args: any[]) => Error) | Error | object;\nconst isToThrowExpected = (v: unknown): v is ToThrowExpected =>\n  typeof v === 'string' ||\n  typeof v === 'function' ||\n  v instanceof RegExp ||\n  v instanceof Error ||\n  (v != null && typeof v === 'object');","tryCatchPattern":"try {\n  expect(fn).toThrow(expected);\n} catch (e) {\n  if (e instanceof Error && /must be a string or regular expression or class or error/.test(e.message)) {\n    console.error('expected was an unsupported type:', typeof expected, expected);\n  }\n  throw e;\n}","preventionTips":["Pass a message string, RegExp pattern, error class, or Error-shaped object.","Do not pass numeric status codes or booleans as the expected value.","Pass the class (`Error`), not an instance (`new Error()`), when matching by type — though instances are accepted as shape objects."],"tags":["jest","expect","type-validation","assertion","error-handling"],"analyzedSha":"f49721c78e195558b40913977c9230f5b7f559d8","analyzedAt":"2026-08-03T20:16:28.571Z","schemaVersion":2}