vitest-dev/vitest · error · TypeError
vi.mock() expects a string path, but received a
Error message
vi.mock() expects a string path, but received a ${typeof path} What it means
`vi.mock(path, factory)` registers a module mock and requires `path` to be a string so the resolver can locate the module. The browser hints layer throws a `TypeError` (with the runtime `typeof`) when a non-string is passed, before queuing the mock.
Solutions
- Pass the module path as a string literal: `vi.mock('./db')`.
- Use `vi.mocked(importedFn)` to type-check an already-imported mock, not `vi.mock`.
- If the path is dynamic, ensure the variable is a string at call time.
Example fix
// before
import * as db from './db'
vi.mock(db)
// after
vi.mock('./db') Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof path !== 'string') {
throw new TypeError(`vi.mock requires a string path, got ${typeof path}`)
} Type guard
const isPathString = (v: unknown): v is string => typeof v === 'string'
Prevention
- Pass the module path as a string literal to vi.mock.
- Use vi.mocked() to type-check an imported mock, not vi.mock().
- Avoid passing imported namespace objects as the path.
When it happens
Trigger: Passing a module object, a Promise, a number, or an imported binding object to `vi.mock` as the first argument; passing a variable that was reassigned away from a string.
Common situations: Confusing `vi.mock` (string path) with `vi.mocked` (wrapped import); passing the imported module itself instead of its path; copy-paste where the path was replaced by a value.
Related errors
- vi.doMock() expects a string path, but received a
- vi.doUnmock() expects a string path, but received a
- vi.hoisted() expects a function, but received a
- vi.unmock() expects a string path, but received a
- Vitest mocker was not initialized in this environment. vi.
AI-assisted analysis of vitest-dev/vitest@1fa9837ec2 (2026-08-11).
Data as JSON: /api/errors/563053fb6311d434.
Report an issue: GitHub.
Appendix: source
Thrown at packages/mocker/src/browser/hints.ts:64
)
},
},
)
}
return {
hoisted<T>(factory: () => T): T {
if (typeof factory !== 'function') {
throw new TypeError(
`vi.hoisted() expects a function, but received a ${typeof factory}`,
)
}
return factory()
},
mock(path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper): void {
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,
),
)
: factory,
)
},View on GitHub (pinned to 1fa9837ec2)