{"id":"fabf918ae58707c9","repo":"jestjs/jest","slug":"received-value-must-not-be-null-nor-undefined","errorCode":null,"errorMessage":"received value must not be null nor undefined","messagePattern":"received value must not be null nor undefined","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/expect/src/matchers.ts","lineNumber":475,"sourceCode":"      // eslint-disable-next-line prefer-template\n      matcherHint(matcherName, undefined, '', options) +\n      '\\n\\n' +\n      `Received: ${printReceived(received)}`;\n\n    return {message, pass};\n  },\n\n  toContain(received: ContainIterable | string, expected: unknown) {\n    const matcherName = 'toContain';\n    const isNot = this.isNot;\n    const options: MatcherHintOptions = {\n      comment: 'indexOf',\n      isNot,\n      promise: this.promise,\n    };\n\n    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(","sourceCodeStart":457,"sourceCodeEnd":493,"githubUrl":"https://github.com/jestjs/jest/blob/f49721c78e195558b40913977c9230f5b7f559d8/packages/expect/src/matchers.ts#L457-L493","documentation":"Thrown by `toContain` (matchers.ts:465) when the value passed to `expect(...)` is `null` or `undefined`. `toContain` needs a string or iterable (array/Set/Nodelist/etc.) to call `indexOf` or spread; a nullish value would either throw on `.indexOf` or produce an empty spread that hides the real defect. Jest throws a plain `Error` (not TypeError) early so the failure message points at the nullish received value rather than a cryptic `Cannot read properties of null`.","triggerScenarios":"Calling `expect(maybeArray).toContain(item)` where `maybeArray` is `undefined` because the function returned nothing, the property doesn't exist on the object, or an optional chain short-circuited. Also `expect(querySelector(...)).toContain(node)` when the selector matched nothing and returned null.","commonSituations":"A function under test returns `undefined` on a missing path; an API response shape changed and the expected array is gone; a `find()` returned undefined; DOM queries returning null when the element isn't rendered; default parameter values not applied.","solutions":["Find why the value is nullish — log it and trace the producer.","Provide a fallback in the source: `return result ?? [];` so an empty array, not undefined, is returned.","If nullish is genuinely possible, assert that first: `expect(arr).toEqual(expect.any(Array));` then `.toContain`.","If asserting optional presence, guard with `if (arr) expect(arr).toContain(item);`."],"exampleFix":"// before\nexpect(user.roles).toContain('admin'); // user.roles is undefined\n\n// after\nexpect(user.roles ?? []).toContain('admin');","handlingStrategy":"validation","validationCode":"if (received == null) {\n  throw new Error(`received is ${received}; cannot use toContain`);\n}\nexpect(received).toContain(item);","typeGuard":"const isContainable = (v: unknown): v is string | Array<unknown> | Set<unknown> =>\n  v != null && (typeof v === 'string' || Array.isArray(v) || typeof v[Symbol.iterator] === 'function');","tryCatchPattern":"try {\n  expect(received).toContain(item);\n} catch (e) {\n  if (e instanceof Error && /must not be null nor undefined/.test(e.message)) {\n    console.error('received was nullish; check the producer');\n  }\n  throw e;\n}","preventionTips":["Default producers to return `[]` or `''` instead of `undefined` for collections.","Assert presence first: `expect(arr).toBeDefined()` before `.toContain`.","Use TypeScript strict null checks so optional returns are explicit."],"tags":["jest","expect","null-check","assertion","arrays","iterable"],"analyzedSha":"f49721c78e195558b40913977c9230f5b7f559d8","analyzedAt":"2026-08-03T20:16:28.571Z","schemaVersion":2}