Skip to content

Mock module with import(path) to be resistant to file renaming #5671

@zirkelc

Description

@zirkelc

Clear and concise description of the problem

Traditional file imports like import { foo } from '../bar' or const foo = await import('../bar') have the advantage, that when the file bar is being renamed or moved to a different folder, TypeScript automatically renames the path on all import occurrences.

Mocking with vi.mock('../bar') doesn't get the same renaming support. When you rename/move the file bar, the import statements are updated but the mocks are not. That means suddenly, the tests fail and it may not be obvious why.

Here is a short video in case it's not clear:

2024-05-05_13-22-29.mp4

Another disadvantage, although less important, is the navigation feature that editors provide for import statements. On macOS with CMD+mouse click you can easily navigate to the source file.

Suggested solution

If it were possible to provide a dynamic import to mock like vi.mock(import("./bar")) so we would get the auto-renaming from TypeScript. Then, the Vitest could apply a similar logic to vi.mock() like it does for vi.hoisted(). It could rewrite all mocks to replace the vi.mock(import("./bar")) with the old vi.mock("./bar"). Maybe it is also possible to work with the Promise from import() directly inside vi.mock and it is not even necessary to rewrite all mock statements.

Alternative

No response

Additional context

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p2-nice-to-haveNot breaking anything but nice to have (priority)

    Type

    No type

    Projects

    Status

    Approved

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions