vitest-dev/vitest · error · TypeError
vi.mock() expects a string path, but received a ${typeof pat
Error message
vi.mock() expects a string path, but received a ${typeof path} What it means
`vi.mock(path, factory)` queues a module mock identified by a string module path. The guard rejects any non-string `path` with a `TypeError` reporting the received type, because the mocker keys mocks by resolved string path and cannot queue a mock for a non-string identifier. The signature accepts `string | Promise<unknown>` for type-level flexibility but enforces string at runtime.
Source
Thrown at packages/vitest/src/integrations/vi.ts:648
catch (error) {
if (error instanceof Error && !error.stack?.includes('__VITEST_HELPER__')) {
copyStackTrace(error, stackTraceError)
}
throw error
}
})()
}
return result
} as any
},
hoisted<T>(factory: () => T): T {
assertTypes(factory, '"vi.hoisted" factory', ['function'])
return factory()
},
mock(path: string | Promise<unknown>, factory?: MockOptions | MockFactoryWithHelper) {
if (typeof path !== 'string') {
throw new TypeError(
`vi.mock() expects a string path, but received a ${typeof path}`,
)
}
const importer = getImporter('mock')
_mocker().queueMock(
path,
importer,
typeof factory === 'function'
? () =>
factory(() =>
_mocker().importActual(
path,
importer,
_mocker().getMockContext().callstack,
),
)
: factory,
)View on GitHub (pinned to d568f8ce37)
Solutions
- Pass the module specifier as a literal string: `vi.mock('./api')`.
- If the path is dynamic, ensure the variable is a string before calling (e.g. `vi.mock(String(name))`).
- Use `vi.doMock` with a runtime string if the path is not statically known.
Example fix
// before
vi.mock(import('./api'))
// after
vi.mock('./api') Defensive patterns
Strategy: type-guard
Validate before calling
function mockPath(path: unknown) {
if (typeof path !== 'string') throw new TypeError(`vi.mock expects string, got ${typeof path}`)
vi.mock(path)
} Type guard
function isModulePath(v: unknown): v is string { return typeof v === 'string' && v.length > 0 } Prevention
- Always pass a string literal module specifier to `vi.mock`.
- Use `vi.doMock` for runtime-computed string paths.
When it happens
Trigger: Calling `vi.mock(123)`, `vi.mock(someObject)`, `vi.mock(import('./mod'))` (passing a promise/module namespace), or `vi.mock(undefined)`.
Common situations: Trying to pass a dynamic import expression as the path, or constructing the path from a variable that is accidentally undefined/non-string.
Related errors
- vi.unmock() expects a string path, but received a ${typeof p
- [vitest] vi.mock("${raw}", factory?: () => unknown) is not r
- ${utils.inspect(chain)} is not a `vi.when` instance
- vi.when: the argument must be a mock function created with `
- vi.when: `times` option must be greater than 0
AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03).
Data as JSON: /data/errors/3797218f7f3fd750.json.
Report an issue: GitHub.