vitest-dev/vitest · error · TypeError

[vitest] vi.mock("${raw}", factory?: () => unknown) is not r

Error message

[vitest] vi.mock("${raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?

What it means

A `vi.mock` factory must return a module-namespace object — either `{ default, ...named }` or a bag of named exports. `assertValidExports` rejects `null`, primitives, and arrays because none of them represent a valid ES/CJS module shape, and the most common cause is forgetting to wrap a single value under a `default` key.

Source

Thrown at packages/mocker/src/registry.ts:327

      id: this.id,
      raw: this.raw,
    }
  }
}

function createHelpfulError(cause: Error) {
  const error = new Error(
    '[vitest] There was an error when mocking a module. '
    + 'If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. '
    + 'Read more: https://vitest.dev/api/vi.html#vi-mock',
  )
  error.cause = cause
  return error
}

function assertValidExports(raw: string, exports: any) {
  if (exports === null || typeof exports !== 'object' || Array.isArray(exports)) {
    throw new TypeError(
      `[vitest] vi.mock("${raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`,
    )
  }
}

export interface ManualMockedModuleSerialized {
  type: 'manual'
  url: string
  id: string
  raw: string
}

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Wrap a single value as the default export: `() => ({ default: value })`.
  2. Return named exports as an object: `() => ({ add: vi.fn(), sub: vi.fn() })`.
  3. For async factories, resolve to an object: `async () => ({ default: await load() })`.

Example fix

// before
vi.mock('./db', () => 42)

// after
vi.mock('./db', () => ({
  default: 42,
}))
Defensive patterns

Strategy: validation

Validate before calling

function mockModule(specifier: string, factory: () => unknown) {
  const exports = factory()
  if (exports === null || typeof exports !== 'object' || Array.isArray(exports)) {
    throw new TypeError(
      `vi.mock('${specifier}') factory must return an object (module namespace). ` +
      `Wrap a single value: () => ({ default: value }).`,
    )
  }
  vi.mock(specifier, factory as () => any)
}

Type guard

function isValidMockExports(v: unknown): v is Record<string, unknown> {
  return v !== null && typeof v === 'object' && !Array.isArray(v)
}

Prevention

When it happens

Trigger: `vi.mock('m', () => 42)`, `() => null`, `() => [1, 2, 3]`, `() => 'string'`, or an async factory returning a non-object. Also fires if the factory returns a Promise that resolves to a non-object.

Common situations: Mocking a default export and returning the value directly instead of `{ default: value }`; returning a class instance meant as the default; returning an array of items; factory that conditionally returns `null`.

Related errors


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