Skip to content
jshacks.dev
Testing

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.

1 min read
Summarize in AI

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.

dates.jsJavaScript
export function today() {
  return new Date().toISOString().slice(0, 10);
}

export function format(date) {
  return date.toUpperCase();
}
dates.test.jsJavaScript
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');
});
Text
 ✓ 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.

Taggedvitest
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.