vitest-dev/vitest · error · Error

Expected is not a String or a RegExp

Error message

Expected is not a String or a RegExp

What it means

Thrown by the StringMatching asymmetric matcher constructor when the sample is neither a string nor a RegExp (checked via isA('String') and isA('RegExp')). StringMatching compiles the sample into a RegExp to test substring/pattern inclusion.

Source

Thrown at packages/expect/src/jest-asymmetric-matchers.ts:320

      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): boolean {
    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 d568f8ce37)

Solutions

  1. Pass a string pattern or a RegExp: expect.stringMatching(/^foo/) or expect.stringMatching('foo').
  2. For object shape checks use objectContaining; for arrays use arrayContaining.
  3. Validate the variable is string|RegExp before constructing the matcher.

Example fix

// before
expect(msg).toEqual(expect.stringMatching(123))
// after
expect(msg).toEqual(expect.stringMatching(/error \d+/))
Defensive patterns

Strategy: type-guard

Validate before calling

function asStringOrRegex(v: unknown): string | RegExp {
  if (typeof v !== 'string' && !(v instanceof RegExp)) {
    throw new TypeError(`stringMatching needs string|RegExp, got ${typeof v}`)
  }
  return v
}
expect(msg).toEqual(expect.stringMatching(asStringOrRegex(pattern)))

Type guard

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

Prevention

When it happens

Trigger: Constructing expect.stringMatching(value) where value is a number, object, null, etc. Neither guard passes so the constructor throws before compiling.

Common situations: Passing a RegExp flags object, a number, or a non-string variable; confusing stringMatching with a generic matcher; a refactor that changed the sample type.

Related errors


AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03). Data as JSON: /data/errors/415a72f625cb13ea.json. Report an issue: GitHub.