Asserting on Mocks in Vitest

From the Vitest cheat sheet ยท Mock Functions ยท verified Nov 2026

Asserting on Mocks

Check how a mock was called, what it returned, and in which order

typescript
expect(fn).toHaveBeenCalled()
expect(fn).toHaveBeenCalledTimes(2)
expect(fn).toHaveBeenCalledWith('ada', { admin: true })
expect(fn).toHaveBeenLastCalledWith('grace')
expect(fn).toHaveBeenCalledExactlyOnceWith('ada')
expect(fn).toHaveReturnedWith(42)
๐Ÿ“Œ Pass the mock itself, not a call: expect(fn), not expect(fn())
๐Ÿ’ก toHaveBeenCalledExactlyOnceWith checks count and args together
๐Ÿ” mock.calls is an array of argument arrays, one per call
โšก Mix in matchers: toHaveBeenCalledWith(expect.any(String))
toHaveBeenCalledWithmock.callsspy-assertions

Continue with Vitest

Save the full cheat sheet or work through every related task.

More Vitest tasks

Back to the full Vitest cheat sheet