vitest-dev/vitest · error · TypeError

vi.hoisted() expects a function, but received a

Error message

vi.hoisted() expects a function, but received a ${typeof factory}

What it means

`vi.hoisted` hoists a factory to the top of the module so its return value is available before imports. The factory must be a function; otherwise hoisting has nothing to invoke. The browser hints layer throws a `TypeError` reporting the actual `typeof` value received.

Solutions

  1. Wrap the value in a zero-arg function: `vi.hoisted(() => value)`.
  2. If you intended to pass config, note `vi.hoisted` takes only a factory — return the config from it.
  3. Double-check the call site after refactors that inline the factory body.

Example fix

// before
const mock = vi.hoisted({ foo: 'bar' })

// after
const mock = vi.hoisted(() => ({ foo: 'bar' }))
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof factory !== 'function') {
  throw new TypeError(`vi.hoisted requires a function, got ${typeof factory}`)
}

Type guard

const isFactory = (v: unknown): v is () => unknown =>
  typeof v === 'function'

Prevention

When it happens

Trigger: Calling `vi.hoisted(42)`, `vi.hoisted('value')`, `vi.hoisted(undefined)`, or passing a config object by mistake instead of a factory function.

Common situations: Copy-paste error where a value is passed instead of `() => value`; refactor that changed the factory into a direct call (`vi.hoisted(makeMock())` instead of `vi.hoisted(() => makeMock())`).

Related errors


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

Appendix: source

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

      // @ts-expect-error injected by the plugin
      ? globalThis[globalThisAccessor]
      : new Proxy(
          {} as any,
          {
            get(_, name) {
              throw new Error(
                'Vitest mocker was not initialized in this environment. '
                + `vi.${String(name)}() is forbidden.`,
              )
            },
          },
        )
  }

  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'
          ? () =>

View on GitHub (pinned to 1fa9837ec2)