vitest-dev/vitest · error · TypeError

vi.doMock() expects a string path, but received a

Error message

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

What it means

Thrown by `vi.doMock(path, factory)` when `path` is not a string. Unlike `vi.mock`, `vi.doMock` is NOT hoisted — it runs at the call site and is intended for per-test dynamic mocking — but it still requires a string module specifier for resolution. A non-string path raises a TypeError.

Solutions

  1. Pass a string specifier: `vi.doMock('./myModule', () => {...})`.
  2. If the path is dynamic, ensure the variable is a string at call time (guard/log before calling).
  3. Confirm you are passing the specifier and not the imported module object.

Example fix

// before
vi.doMock(await import('./myModule'))

// after
vi.doMock('./myModule', () => ({ foo: 'mocked' }))
Defensive patterns

Strategy: type-guard

Validate before calling

function doMockSafe(path, factory) {
  if (typeof path !== 'string') throw new TypeError('vi.doMock requires a string path')
  return vi.doMock(path, factory)
}

Type guard

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

Prevention

When it happens

Trigger: Calling `vi.doMock(someObject)` or `vi.doMock(promise)`; passing a variable that resolved to a non-string; passing an imported module namespace instead of its path.

Common situations: Switching from `vi.mock` to `vi.doMock` for scoped mocking but keeping a non-string argument; dynamically building a path that is undefined at call time; refactoring errors.

Related errors


AI-assisted analysis of vitest-dev/vitest@1fa9837ec2 (2026-08-11). Data as JSON: /api/errors/c7a579bc6e891043. Report an issue: GitHub.

Appendix: source

Thrown at packages/vitest/src/integrations/vi.ts:680

                  _mocker().getMockContext().callstack,
                ),
              )
          : factory,
      )
    },

    unmock(path: string | Promise<unknown>) {
      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?: MockOptions | MockFactoryWithHelper) {
      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,
                  _mocker().getMockContext().callstack,
                ),
              )
          : factory,
      )

View on GitHub (pinned to 1fa9837ec2)