Mock part of a module with importOriginal
Mock only some exports of a module in Vitest by spreading importOriginal in the vi.mock factory, so the other exports keep their real code.
A full mock hides the whole module, which is too much when you only need to fake one function. The factory receives importOriginal, which loads the real module for you to spread.
export function today() {
return new Date().toISOString().slice(0, 10);
}
export function format(date) {
return date.toUpperCase();
}import { test, expect, vi } from 'vitest';
import { today, format } from './dates.js';
vi.mock('./dates.js', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
today: () => '2026-01-02',
};
});
test('fakes only today', () => {
expect(today()).toBe('2026-01-02');
expect(format('abc')).toBe('ABC');
}); ✓ dates.test.js (1 test)
Test Files 1 passed (1)
Tests 1 passed (1)importOriginal returns the real exports, and the object spread keeps format while replacing today. The result is a partial mock. Without the spread, format would be undefined and Vitest throws an error telling you that the export was not defined in the factory. See partial mocking.
Calls between functions inside the original module are not affected: if format called today internally, it would still call the real one, because the replacement only changes what other modules import. Move the clock behind a parameter, or use fake timers, when that matters.