tezvyn:

Vitest Mocking: Isolating Code with `vi.mock`

Source: vitest.devintermediate

Vitest's `vi.mock` replaces a module with a fake version, isolating your code for tests. This is key for preventing real network or database calls. The footgun: calls are "hoisted" to the top of the file, running before other code and breaking variable access.

Vitest's `vi.mock` replaces a real module with a fake one, isolating the code under test. Think of it as swapping a live API client for a dummy that returns predictable data. This is essential for unit testing without real network calls or database writes. The main footgun is hoisting: `vi.mock` is moved to the top of your file before imports, so you can't use variables defined in the test scope inside your mock factory.

Read the original → vitest.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

Vitest Mocking: Isolating Code with `vi.mock` · Tezvyn