← All notes

Vitest mocking builds fake stand-ins through the vi helper

Answer: Mocking means creating a fake version of an internal or external service. Vitest exposes that work through the vi helper, which you import from vitest or use globally when global is enabled. If you are not familiar with vi.fn, vi.mock or vi.spyOn methods, the API section covers them.

Resetting and limits

Clear or restore mocks before or after each test so mock state does not leak between runs. A vi.mock call is hoisted to the top of the file and runs before imports. Some vi.spyOn patterns on module exports do not work in browser mode.

The spy helpers in source

fn wraps a function in a mock instance, and if you pass a value that is already a mock it returns that same function. isMockFunction is true when fn is a function, '_isMockFunction' is in fn, and fn._isMockFunction === true. spyOn requires a defined object as its first argument.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources and notices: Vitest documentation and source (vitest-dev/vitest): Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors; MIT (https://raw.githubusercontent.com/vitest-dev/vitest/main/LICENSE). Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Vitest docs and Vitest source (vitest-dev/vitest), MIT. Notices: Vitest documentation and source (vitest-dev/vitest): Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors; MIT (https://raw.githubusercontent.com/vitest-dev/vitest/main/LICENSE).

Cite this

Permanent ID: iil:note:28d9g342

iinventedlight. 2026. "Vitest mocking builds fake stand-ins through the vi helper." iinventedlight Library, iil:note:28d9g342, version of 2026-11-11. https://iinventedlight.com/library/notes/vitest-mocking/. License: CC-BY-4.0.

@misc{iil_note_28d9g342,
  author = {{iinventedlight}},
  title = {{Vitest mocking builds fake stand-ins through the vi helper}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-11},
  url = {https://iinventedlight.com/library/notes/vitest-mocking/},
  note = {Permanent ID iil:note:28d9g342. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/vitest-mocking.md.