Conditional Mocks with vi.when in Vitest
From the Vitest cheat sheet · Mock Functions · verified Nov 2026
Conditional Mocks with vi.when
Return different values per argument without hand-written if/else (5.0+)
typescript
const getUser = vi.fn()
vi.when(getUser)
.calledWith(1).thenReturn({ id: 1, name: 'Ada' })
.calledWith(2).thenReturn({ id: 2, name: 'Grace' })
getUser(1) // { id: 1, name: 'Ada' }
getUser(3) // undefined (falls through)📌 New in Vitest 5; replaces if/else inside mockImplementation
⚠️ Overlapping args like 1 and expect.any(Number) share one slot
💡 Use onUnmatched for a catch-all instead of an overlapping matcher
⚡ The newest behavior for the same args is tried first (LIFO)
vi.whenconditional-mockingcalledWith
Continue with Vitest
Save the full cheat sheet or work through every related task.