awslabs/llrt · error · Error

Expected is not a String or a RegExp

Error message

Expected is not a String or a RegExp

What it means

StringMatching builds a RegExp from its sample, which must be a string or a RegExp. The constructor throws this plain Error for any other type so invalid patterns fail fast instead of producing a runtime RegExp construction error inside matching.

Solutions

  1. Pass a string pattern: expect.stringMatching('^abc$').
  2. Pass a RegExp literal: expect.stringMatching(/abc/i).
  3. Convert a RegExp-like object to a real RegExp via new RegExp(obj.pattern, obj.flags).
  4. Fix the undefined variable holding the pattern.

Example fix

// before
expect(err.message).toEqual(expect.stringMatching(404));
// after
expect(err.message).toEqual(expect.stringMatching(/404/));
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof sample !== 'string' && !(sample instanceof RegExp)) throw new TypeError('stringMatching sample must be a string or RegExp');

Type guard

const isPattern = (v: unknown): v is string | RegExp => typeof v === 'string' || v instanceof RegExp;

Try / catch

try { expect(msg).toEqual(expect.stringMatching(sample)); } catch (e) { /* bad pattern sample */ }

Prevention

When it happens

Trigger: expect.stringMatching(42), expect.stringMatching(null), expect.stringMatching({pattern:'x'}) — any sample that is neither string nor RegExp.

Common situations: Passing a regex-like object from another library, passing a number pattern, or a variable expected to hold a pattern string that is undefined.

Related errors


AI-assisted analysis of awslabs/llrt@742fc00b82 (2026-09-12). Data as JSON: /api/errors/1993f5f3a9b35e80. Report an issue: GitHub.

Appendix: source

Thrown at llrt_core/src/modules/js/@llrt/expect/jest-asymmetric-matchers.ts:277

    if (this.sample === Function) return "function";

    if (this.sample === Object) return "object";

    if (this.sample === Boolean) return "boolean";

    return this.fnNameFor(this.sample);
  }

  toAsymmetricMatcher() {
    return `Any<${this.fnNameFor(this.sample)}>`;
  }
}

export 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: string) {
    const result = isA("String", other) && this.sample.test(other);

    return this.inverse ? !result : result;
  }

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

  getExpectedType() {
    return "string";
  }
}

View on GitHub (pinned to 742fc00b82)