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

  1. Pass a RegExp literal: expect.stringMatching(/^user-/).
  2. Pass a string pattern: expect.stringMatching('user-').
  3. 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

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


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)