vitest-dev/vitest · error · TypeError

vi.doMock() expects a string path, but received a ${typeof p

Error message

vi.doMock() expects a string path, but received a ${typeof path}

What it means

Thrown at packages/mocker/src/browser/hints.ts:94-98 as a TypeError when vi.doMock() is called with a non-string first argument. vi.doMock is the non-hoisted variant of vi.mock and likewise requires a string module specifier to resolve and register the mock at call time.

Source

Thrown at packages/mocker/src/browser/hints.ts:95

                  importer,
                ),
              )
          : factory,
      )
    },

    unmock(path: string | Promise<unknown>): void {
      if (typeof path !== 'string') {
        throw new TypeError(
          `vi.unmock() expects a string path, but received a ${typeof path}`,
        )
      }
      _mocker().queueUnmock(path, getImporter('unmock'))
    },

    doMock(path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper): void {
      if (typeof path !== 'string') {
        throw new TypeError(
          `vi.doMock() expects a string path, but received a ${typeof path}`,
        )
      }
      const importer = getImporter('doMock')
      _mocker().queueMock(
        path,
        importer,
        typeof factory === 'function'
          ? () =>
              factory(() =>
                _mocker().importActual(
                  path,
                  importer,
                ),
              )
          : factory,
      )
    },

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Pass a string literal module path: vi.doMock('./logger').
  2. If computing the path dynamically, validate it is a string before calling doMock.

Example fix

// before
vi.doMock(import('./logger'))

// after
vi.doMock('./logger')
Defensive patterns

Strategy: type-guard

Validate before calling

function doMockIfString(path: unknown, factory?: () => any) {
  if (typeof path !== 'string') {
    throw new TypeError(`vi.doMock requires a string path, got ${typeof path}`)
  }
  vi.doMock(path, factory)
}

Type guard

function isModulePath(path: unknown): path is string {
  return typeof path === 'string' && path.length > 0
}

Prevention

When it happens

Trigger: Calling vi.doMock(undefined), vi.doMock(someVar) where someVar is not a string, or vi.doMock(import('./x')) that escaped the transform rewrite.

Common situations: Using vi.doMock inside an async function with a dynamically computed path that resolved to undefined; refactoring from vi.mock to vi.doMock and forgetting the path argument.

Related errors


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