jestjs/jest · error · Error

Expected is not a string

Error message

Expected is not a string

What it means

StringContaining's constructor validates the sample with isA('String', sample), accepting both primitives and boxed String objects. Anything else (number, regex, object) throws immediately at construction. expect.stringContaining is meant to assert a substring is present in a received string.

Source

Thrown at packages/expect/src/asymmetricMatchers.ts:303

      }
    }

    return this.inverse ? !result : result;
  }

  toString() {
    return `Object${this.inverse ? 'Not' : ''}Containing`;
  }

  override getExpectedType() {
    return 'object';
  }
}

class StringContaining extends AsymmetricMatcher<string> {
  constructor(sample: string, inverse = false) {
    if (!isA('String', sample)) {
      throw new Error('Expected is not a string');
    }
    super(sample, inverse);
  }

  asymmetricMatch(other: unknown) {
    const result = isA<string>('String', other) && other.includes(this.sample);

    return this.inverse ? !result : result;
  }

  toString() {
    return `String${this.inverse ? 'Not' : ''}Containing`;
  }

  override getExpectedType() {
    return 'string';
  }
}

View on GitHub (pinned to f49721c78e)

Solutions

  1. Pass a string substring: expect.stringContaining('hello').
  2. For regex matching use expect.stringMatching(/pattern/).
  3. Coerce when appropriate: expect.stringContaining(String(val)).

Example fix

// before
expect(name).toEqual(expect.stringContaining(/J.*/i));

// after — use stringMatching for regex
expect(name).toEqual(expect.stringMatching(/^J/i));
// or pass a literal substring
expect(name).toEqual(expect.stringContaining('J'));
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof sample !== 'string' && !(sample instanceof String)) {
  throw new TypeError('expect.stringContaining needs a string');
}
expect.stringContaining(sample);

Type guard

function isStringLike(x: unknown): x is string | String {
  return typeof x === 'string' || x instanceof String;
}

Try / catch

// constructor throws synchronously — validate the sample before calling

Prevention

When it happens

Trigger: Calling expect.stringContaining(123), expect.stringContaining(/re/) (use stringMatching instead), expect.stringContaining(undefined), or expect.stringContaining(someObject).

Common situations: Passing a RegExp where a substring was intended; passing a variable whose value is not a string; mixing up stringContaining and stringMatching.

Related errors


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