jestjs/jest · error · Error

Expected is not a String or a RegExp

Error message

Expected is not a String or a RegExp

What it means

StringMatching's constructor accepts either a String or a RegExp (it will wrap a string sample with new RegExp(sample)); any other type throws. This makes stringMatching the flexible matcher (substring-as-regex or real regex), complementing stringContaining which is strictly substring.

Source

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

  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';
  }
}

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

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

    return this.inverse ? !result : result;
  }

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

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

View on GitHub (pinned to f49721c78e)

Solutions

  1. Pass a regex: expect.stringMatching(/^foo/), or a string that is a valid regex pattern: expect.stringMatching('foo').
  2. Ensure the value is defined and is a string or RegExp before constructing the matcher.
  3. Use expect.stringContaining if you want a literal substring with no regex semantics.

Example fix

// before
expect(msg).toEqual(expect.stringMatching(404));

// after
expect(msg).toEqual(expect.stringMatching(/404/));
// or
expect(msg).toEqual(expect.stringContaining('404'));
Defensive patterns

Strategy: type-guard

Validate before calling

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

Type guard

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

Try / catch

// constructor throws synchronously — validate the sample before calling

Prevention

When it happens

Trigger: Calling expect.stringMatching(123), expect.stringMatching(null), expect.stringMatching({}), or expect.stringMatching(undefined).

Common situations: Passing a number expecting implicit coercion; passing an object by mistake; a variable that was supposed to hold a regex/string but is undefined.

Related errors


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