{"id":"ec3637454917c633","repo":"jestjs/jest","slug":"expected-value-must-be-a-string-if-received-value","errorCode":null,"errorMessage":"expected value must be a string if received value is a string","messagePattern":"expected value must be a string if received value is a string","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"packages/expect/src/matchers.ts","lineNumber":492,"sourceCode":"    if (received == null) {\n      throw new Error(\n        matcherErrorMessage(\n          matcherHint(matcherName, undefined, undefined, options),\n          `${RECEIVED_COLOR('received')} value must not be null nor undefined`,\n          printWithType('Received', received, printReceived),\n        ),\n      );\n    }\n\n    if (typeof received === 'string') {\n      const wrongTypeErrorMessage = `${EXPECTED_COLOR(\n        'expected',\n      )} value must be a string if ${RECEIVED_COLOR(\n        'received',\n      )} value is a string`;\n\n      if (typeof expected !== 'string') {\n        throw new TypeError(\n          matcherErrorMessage(\n            matcherHint(matcherName, received, String(expected), options),\n            wrongTypeErrorMessage,\n            // eslint-disable-next-line prefer-template\n            printWithType('Expected', expected, printExpected) +\n              '\\n' +\n              printWithType('Received', received, printReceived),\n          ),\n        );\n      }\n\n      const index = received.indexOf(String(expected));\n      const pass = index !== -1;\n\n      const message = () => {\n        const labelExpected = `Expected ${\n          typeof expected === 'string' ? 'substring' : 'value'\n        }`;","sourceCodeStart":474,"sourceCodeEnd":510,"githubUrl":"https://github.com/jestjs/jest/blob/f49721c78e195558b40913977c9230f5b7f559d8/packages/expect/src/matchers.ts#L474-L510","documentation":"Thrown by `toContain` (matchers.ts:484-502) specifically when the received value is a string but the expected argument is not. Because `String.prototype.indexOf` only accepts string search values, Jest enforces symmetry: a string received demands a string expected, otherwise it throws a `TypeError` rather than silently returning -1. The error includes both `printWithType` for Expected and Received.","triggerScenarios":"Calling `expect('hello world').toContain(5)` (number), `expect(text).toContain(/foo/)` (regex — use `toMatch` instead), `expect(html).toContain({tag: 'div'})` (object), or `expect(str).toContain(undefined)` when an optional value was not supplied.","commonSituations":"Confusing `toContain` with `toMatch` (regex matching); passing a parsed token whose type was assumed; substring checks where the search term came from numeric IDs; refactor that changed an argument type from string to number.","solutions":["If matching a pattern, switch to `toMatch(/foo/)` or `toMatch('foo')`.","Coerce the expected value to a string: `.toContain(String(id))`.","If you meant to check array membership, make sure the received value is an array, not a string.","Log `typeof expected` to confirm it is not undefined/object before the assertion."],"exampleFix":"// before\nexpect(message).toContain(/error/i); // wrong matcher / wrong type\n\n// after\nexpect(message).toMatch(/error/i);","handlingStrategy":"type-guard","validationCode":"if (typeof received === 'string' && typeof expected !== 'string') {\n  throw new Error(`received is a string; expected must also be a string, got ${typeof expected}`);\n}\nexpect(received).toContain(expected);","typeGuard":"const isValidContainArgs = (received: unknown, expected: unknown): boolean =>\n  typeof received !== 'string' || typeof expected === 'string';","tryCatchPattern":"try {\n  expect(received).toContain(expected);\n} catch (e) {\n  if (e instanceof TypeError && /must be a string if/.test(e.message)) {\n    // switch to toMatch for regex, or coerce expected to String\n  }\n  throw e;\n}","preventionTips":["Use `toMatch` for regex matching, not `toContain`.","Coerce numeric search terms with `String(...)` when searching strings.","Keep received/expected types symmetric in helper functions."],"tags":["jest","expect","type-validation","assertion","string","regex"],"analyzedSha":"f49721c78e195558b40913977c9230f5b7f559d8","analyzedAt":"2026-08-03T20:16:28.571Z","schemaVersion":2}