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
- Pass a string pattern or a RegExp: expect.stringMatching(/^foo/) or expect.stringMatching('foo').
- For object shape checks use objectContaining; for arrays use arrayContaining.
- 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
- Type pattern sources as string | RegExp.
- Avoid passing flag-only objects; pass a real RegExp instance.
- Add a lint rule catching non-string/RegExp args to stringMatching.
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
- Expected is not a string
- You must provide an object to ${this.toString()}, not '${typ
- You must provide an array to ${this.toString()}, not '${type
- any() expects to be passed a constructor function. Please pa
- Expected is not a Number
AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03).
Data as JSON: /data/errors/415a72f625cb13ea.json.
Report an issue: GitHub.