vitest-class-mocking

Define inline mock classes inside vi.mock factories to resolve hoisting errors.

9|2|Updated Mar 5, 2026
One-click install
npx skills add https://github.com/DavidTeju/shared-skills --skill vitest-class-mocking
Or copy as Structured Prompt for Agent
Please help me install this Agent Skill.
Skill: vitest-class-mocking
Source: https://github.com/DavidTeju/shared-skills/tree/main/skills/vitest-class-mocking
Command: npx skills add https://github.com/DavidTeju/shared-skills --skill vitest-class-mocking

SYSTEM DOCUMENTATION & REQUIREMENTS

What problem does it solve?

Fix "X is not a constructor" errors when mocking classes in Vitest. Hoisting in Vitest mocks can cause a class to be undefined at mock creation time, leading to runtime failures.

Core Features & Use Cases

  • Inline class definitions inside the vi.mock factory to avoid hoisting issues
  • Use vi.hoisted() for shared mocks across tests
  • Mock multiple related classes with consistent patterns

Quick Start

Inline define mock classes inside the vi.mock() factory to avoid hoisting issues.

Frequently Asked Questions about vitest-class-mocking

High-intent search queries and answers about installing and using this skill.

FAQPage Schema
Why does vi.mock in Vitest throw "is not a constructor" when mocking a class?

Vitest hoists vi.mock calls to the top of the file, causing the mocked class to be undefined at mock creation time and resulting in a runtime "is not a constructor" error. Defining the class inline inside the mock factory resolves this hoisting issue.

How do I mock a class with vi.mock in Vitest without hoisting errors?

To mock a class in Vitest without hoisting errors, define the mock class inline directly inside the vi.mock factory function. This ensures the class definition is available when the mock is created, bypassing hoisting-related reference issues.

Can I use vi.hoisted to share class mocks across multiple Vitest tests?

Yes, you can use vi.hoisted() to create shared class mocks across multiple Vitest tests. This pattern lifts the mock definition outside the vi.mock factory while maintaining proper execution order, ensuring consistent class mocking throughout your test suite.

What is the best way to mock multiple related classes in Vitest?

The best way to mock multiple related classes in Vitest is applying consistent patterns using inline class definitions inside the vi.mock factory. This approach prevents individual hoisting conflicts and maintains reliable constructor behavior across all mocked dependencies.

Does Vitest mock hoisting affect TypeScript unit tests using class-based dependencies?

Yes, Vitest mock hoisting affects TypeScript unit tests by breaking class-based dependencies. When vi.mock attempts to replace a class before its definition is evaluated, the mock returns undefined, causing unit tests requiring new instances to fail at runtime.