vitest-dev / vitest-dev/vitest

.doMock won't mock if called from an imported module

Open
#3,284 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

pending triage
Dominant language
TypeScript
Stars
17.1k
Forks
2k
Avg merge
1d 22h
Merged PRs (30d)
94

Description

Describe the bug

If we have a module A and a module B

Where module A has devDependencies of module C and module B

and, if these conditions are true:

  • vi.doMock for module C is called inside module B
  • we're running vitest run in module A
  • and try to import module C after vi.doMock of module B is called

then, callback of vi.doMock never fires, with no error, and import module C returns a real module C

now, if we remove module C from devDependencies of module A, we have vi.doMock called and import module C returns the mocked value

this discrepancy is what makes me think it's a bug or undefined behaviour: I'd expect either both cases fail, or, hopefully, both cases success

Reproduction

https://github.com/Firfi/vittest-base - serves as "module A"

https://github.com/Firfi/vittest-dependency - serves as "module B"

uuid (https://www.npmjs.com/package/uuid) - serves as "module C" (but it's true with every module I tested with)

yarn install in both and link them together with yarn link (in readme) to see the effect

I have the same effect with a published module, therefore I rule out yarn link issues

System Info
  System:
    OS: macOS 13.2.1
    CPU: (8) arm64 Apple M1
    Memory: 111.55 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 18.16.0 - ~/.n/bin/node
    Yarn: 1.22.19 - /opt/homebrew/bin/yarn
    npm: 9.5.1 - ~/.n/bin/npm
  Browsers:
    Chrome: 112.0.5615.137
    Edge: 112.0.1722.68
    Firefox: 109.0.1
    Safari: 16.3
Used Package Manager

yarn

Validations

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the linked vittest-base and vittest-dependency reproductions with yarn, using vitest run, and compare behavior when uuid is or is not in module A's devDependencies. Trace the vi.doMock call from module B and the later import of uuid. Done means both dependency layouts consistently invoke the mock callback and return the mocked value, with a regression test covering the discrepancy.

Written by the indexing model from the issue text.

Assessment

Tech stack
nodejs, typescript
Domain
testing-qa, tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.