Course contentsShow
← React
Lesson 2077 of 2,39646. Testing React with RTLFree lesson

Mocking Default vs Named Exports

Different syntax for mocking default exports versus named exports, and handling mixed export modules.

Mocking Default vs Named Exports

You'll learn how to correctly mock modules that use different export styles—default, named, or both—because the syntax varies significantly.

Why Export Styles Matter in Mocking

When you mock a module with vi.mock(), Vitest needs to know how that module exports its functionality. A module that uses export default Button requires different mocking syntax than one using export const Button = .... Get this wrong, and your mock won't be found—your test will still import the real code.

Think of it like addressing mail: default exports live at the "main address" of the module, while named exports are like apartment numbers. You need the correct address format to reach the right destination.

Syntax Differences

Default export mock:

vi.mock('./Button', () => ({
  default: vi.fn(() => <div>Mocked Button</div>)
}));

Named export mock:

vi.mock('./utils', () => ({
  formatDate: vi.fn(),
  parseDate: vi.fn()
}));

Mixed exports (both default and named):

vi.mock('./api', () => ({
  default: vi.fn(), // mocks the default export
  API_URL: 'http://mock.test', // mocks named export
  fetchUser: vi.fn() // mocks another named export
}));

The Factory Function Pattern

The function you pass to vi.mock() returns an object representing the module's entire export structure. For default exports, that structure must have a default key. For named exports, each export becomes a top-level key in that object.

Key Takeaway: Default exports require a default property in your mock factory, while named exports map directly to object keys—mix both approaches when mocking modules with mixed export styles.