The calledWith() extension allows you to define different behaviors or expectations based on the arguments passed to a mock function. It supports both exact values and matchers, and is fully type-checked.
Decorating existing Vitest mocks
To add calledWith to a function already mocked by Vitest's vi.mock, wrap it with mockFn():
import { vi } from 'vitest';
import { mockFn } from 'vitest-mock-extended';
import { aFunction } from './someThingIWantToMock';
vi.mock('./someThingIWantToMock');
const mockedAFunction = mockFn(aFunction);
// Now you can use calledWith
mockedAFunction.calledWith('foobar').mockReturnValue(true);
const provider = mock<PartyProvider>();
provider.getSongs.calledWith('disco party').mockReturnValue(['Dance the night away', 'Stayin Alive']);
expect(provider.getSongs('disco party')).toEqual(['Dance the night away', 'Stayin Alive']);
// Using Matchers
provider.getSongs.calledWith(any()).mockReturnValue(['Saw her standing there']);
provider.getSongs.calledWith(anyString()).mockReturnValue(['Saw her standing there']);
// Using mockFn for standalone functions
type MyFn = (x: number, y: number) => Promise<string>;
const fn = mockFn<MyFn>();
fn.calledWith(1, 2).mockReturnValue('str');