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
StringMatching (expect.stringMatching) requires the sample to be a String or a RegExp; anything else throws at construction. The sample is then compiled into a RegExp via new RegExp(sample) for matching.
Solutions
- Pass a RegExp literal: expect.stringMatching(/^user-/).
- Pass a string pattern: expect.stringMatching('user-').
- If you have a custom matcher object, convert it to a RegExp first.
Example fix
// before expect(name).toEqual(expect.stringMatching(123)) // after expect(name).toEqual(expect.stringMatching(/^user-\d+$/))
Defensive patterns
Strategy: type-guard
Validate before calling
function asStringMatching(sample) {
if (typeof sample !== 'string' && !(sample instanceof RegExp)) {
throw new TypeError('expect.stringMatching needs a string or RegExp')
}
return expect.stringMatching(sample)
} Type guard
function isStringOrRegExp(v): v is string | RegExp {
return typeof v === 'string' || v instanceof RegExp
} Prevention
- Pass RegExp literals or string patterns to expect.stringMatching.
- Convert foreign-library matcher objects to RegExp before use.
- Distinguish from expect.stringContaining (substring, not pattern).
When it happens
Trigger: expect.stringMatching(sample) with a number, object, null, etc.
Common situations: Passing a number expecting numeric pattern semantics; passing a compiled regex from another lib that is not a native RegExp; passing an object with a custom toString.
Related errors
- any() expects to be passed a constructor function. Please…
- Expected is not a Number
- Expected is not a string
- Precision is not a Number
- You must provide an array to
AI-assisted analysis of vitest-dev/vitest@1fa9837ec2 (2026-08-11).
Data as JSON: /api/errors/415a72f625cb13ea.
Report an issue: GitHub.
Appendix: 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 1fa9837ec2)