jestjs/jest · error · Error

received value must not be null nor undefined

Error message

received value must not be null nor undefined

What it means

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`.

Source

Thrown at packages/expect/src/matchers.ts:475

      // eslint-disable-next-line prefer-template
      matcherHint(matcherName, undefined, '', options) +
      '\n\n' +
      `Received: ${printReceived(received)}`;

    return {message, pass};
  },

  toContain(received: ContainIterable | string, expected: unknown) {
    const matcherName = 'toContain';
    const isNot = this.isNot;
    const options: MatcherHintOptions = {
      comment: 'indexOf',
      isNot,
      promise: this.promise,
    };

    if (received == null) {
      throw new Error(
        matcherErrorMessage(
          matcherHint(matcherName, undefined, undefined, options),
          `${RECEIVED_COLOR('received')} value must not be null nor undefined`,
          printWithType('Received', received, printReceived),
        ),
      );
    }

    if (typeof received === 'string') {
      const wrongTypeErrorMessage = `${EXPECTED_COLOR(
        'expected',
      )} value must be a string if ${RECEIVED_COLOR(
        'received',
      )} value is a string`;

      if (typeof expected !== 'string') {
        throw new TypeError(
          matcherErrorMessage(

View on GitHub (pinned to f49721c78e)

Solutions

  1. Find why the value is nullish — log it and trace the producer.
  2. Provide a fallback in the source: `return result ?? [];` so an empty array, not undefined, is returned.
  3. If nullish is genuinely possible, assert that first: `expect(arr).toEqual(expect.any(Array));` then `.toContain`.
  4. If asserting optional presence, guard with `if (arr) expect(arr).toContain(item);`.

Example fix

// before
expect(user.roles).toContain('admin'); // user.roles is undefined

// after
expect(user.roles ?? []).toContain('admin');
Defensive patterns

Strategy: validation

Validate before calling

if (received == null) {
  throw new Error(`received is ${received}; cannot use toContain`);
}
expect(received).toContain(item);

Type guard

const isContainable = (v: unknown): v is string | Array<unknown> | Set<unknown> =>
  v != null && (typeof v === 'string' || Array.isArray(v) || typeof v[Symbol.iterator] === 'function');

Try / catch

try {
  expect(received).toContain(item);
} catch (e) {
  if (e instanceof Error && /must not be null nor undefined/.test(e.message)) {
    console.error('received was nullish; check the producer');
  }
  throw e;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


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