vitest-dev/vitest · error · Error

[vitest] Unknown mock type: ${type}

Error message

[vitest] Unknown mock type: ${type}

What it means

In the positional register overload, `type` must be one of `'manual'`, `'automock'`, `'autospy'`, or `'redirect'`. Any other string (typo, casing, future type) reaches the final `else` branch and is rejected.

Source

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

      return mock
    }
    else if (type === 'automock' || type === 'autospy') {
      const mock = type === 'automock'
        ? new AutomockedModule(raw, id, url)
        : new AutospiedModule(raw, id, url)
      this.add(mock)
      return mock
    }
    else if (type === 'redirect') {
      if (typeof factoryOrRedirect !== 'string') {
        throw new TypeError('[vitest] Redirect mocks require a redirect string.')
      }
      const mock = new RedirectedModule(raw, id, url, factoryOrRedirect)
      this.add(mock)
      return mock
    }
    else {
      throw new Error(`[vitest] Unknown mock type: ${type}`)
    }
  }

  public delete(id: string): void {
    this.registryByUrl.delete(id)
  }

  public deleteById(id: string): void {
    this.registryById.delete(id)
  }

  public get(id: string): MockedModule | undefined {
    return this.registryByUrl.get(id)
  }

  public getById(id: string): MockedModule | undefined {
    return this.registryById.get(id)
  }

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Use exactly one of: `'manual'`, `'automock'`, `'autospy'`, `'redirect'`.
  2. If `type` comes from a variable, constrain it to the `MockedModuleType` union.
  3. Prefer the serialized-object overload only when you have a real DTO; otherwise use positional with a literal type.

Example fix

// before
registry.register('automocking', raw, id, url)

// after
registry.register('automock', raw, id, url)
Defensive patterns

Strategy: validation

Validate before calling

const VALID_TYPES = new Set(['manual', 'automock', 'autospy', 'redirect'])

function safeRegisterPositional(registry: any, type: unknown, ...rest: unknown[]) {
  if (typeof type !== 'string' || !VALID_TYPES.has(type)) {
    throw new Error(`Unknown mock type '${type}'. Valid: ${[...VALID_TYPES].join(', ')}`)
  }
  ;(registry.register as any)(type, ...rest)
}

Type guard

function isMockedModuleType(v: unknown): v is 'manual' | 'automock' | 'autospy' | 'redirect' {
  return typeof v === 'string'
    && ['manual', 'automock', 'autospy', 'redirect'].includes(v)
}

Prevention

When it happens

Trigger: Calling `registry.register('Manual', raw, id, url, factory)` (wrong casing) or `registry.register('stub', ...)`, or passing `undefined` as the first arg when the others are positional.

Common situations: Typo in programmatic mock setup; dynamically computed type strings; accidental `undefined` first argument.

Related errors


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