vitest-dev/vitest · error · TypeError

.toMatch() expects to receive a string, but got ${typeof act

Error message

.toMatch() expects to receive a string, but got ${typeof actual}

What it means

TypeError thrown synchronously by the toMatch matcher when the actual value (this._obj) is not a string. toMatch only operates on strings (substring or RegExp match); passing any other primitive or object is a programming error, not an assertion failure.

Source

Thrown at packages/expect/src/jest-expect.ts:227

        false,
      ])
      const message
        = stripped === 0
          ? msg
          : `${msg}\n(${stripped} matching ${
            stripped === 1 ? 'property' : 'properties'
          } omitted from actual)`
      throw new AssertionError(message, {
        showDiff: true,
        expected,
        actual: actualSubset,
      })
    }
  })
  def('toMatch', function (expected: string | RegExp) {
    const actual = this._obj as string
    if (typeof actual !== 'string') {
      throw new TypeError(
        `.toMatch() expects to receive a string, but got ${typeof actual}`,
      )
    }

    return this.assert(
      typeof expected === 'string'
        ? actual.includes(expected)
        : actual.match(expected),
      `expected #{this} to match #{exp}`,
      `expected #{this} not to match #{exp}`,
      expected,
      actual,
    )
  })
  def('toContain', function (item) {
    const actual = this._obj as
      | Iterable<unknown>
      | string

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Coerce or assert the value is a string before matching: expect(String(value)).toMatch(/x/) or guard with typeof first.
  2. Fix the upstream code so the value is actually a string.
  3. If matching object shapes, use toMatchObject instead of toMatch.

Example fix

// before
expect(response.statusCode).toMatch('2');
// after
expect(String(response.statusCode)).toMatch(/^2\d{2}$/);
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof actual !== 'string') throw new TypeError(`toMatch target is ${typeof actual}, expected string`);

Type guard

const isString = (v: unknown): v is string => typeof v === 'string';

Prevention

When it happens

Trigger: expect(123).toMatch('foo'); expect(undefined).toMatch(/x/); expect({a:1}).toMatch('a'); expect(null).toMatch('x'). Any call where the assertion target is not a string triggers the typeof actual !== 'string' guard at line 226-229.

Common situations: A variable that the developer believed was a string is actually a number, undefined, or an object — e.g. reading a JSON field that was parsed as a number, or accessing a property that does not exist (undefined). Also common after a refactor changes a function's return type.

Related errors


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