Skip to content

Mocking doesn't work properly with ESM modules #453

@EvHaus

Description

@EvHaus

Describe the bug

Given the following code:

// index.ts
import child_process from 'child_process';
import util from 'util';

export default function main () {
    child_process.exec('test');
}

// index.test.ts
describe('test', () => {
    it('check', () => {
        vi.mock('child_process');

const mockedExec = vi
      .spyOn(child_process, 'exec')
      .mockImplementation((command, callback) => {
        callback();
      });

exec('test');

expect(mockedExec).toHaveBeenCalledWith('test');
    });
});

Everything in the mocking works fine, and the spy is able to get attached.

However, if we:

  • Change the first line to import {exec} from 'child_process';
  • And change the main function to exec('test')

Then mocking fails to get installed. Jest handles this behaviour, but Vitest doesn't.

Reproduction

https://stackblitz.com/edit/node-hgmz55?file=index.test.ts

Note how index.test.ts has two identical tests but for 2 different files.

File works.test.ts works fine, but fails.test.ts doesn't. The only difference is the way the import statement is defined.

System Info

System:
    OS: macOS 12.1
    CPU: (8) x64 Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
    Memory: 139.89 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.13.1 - ~/.nvm/versions/node/v16.13.1/bin/node
    Yarn: 1.22.17 - /usr/local/bin/yarn
    npm: 8.1.2 - ~/.nvm/versions/node/v16.13.1/bin/npm
    Watchman: 2022.01.03.00 - /usr/local/bin/watchman
  Browsers:
    Chrome: 96.0.4664.110
    Chrome Canary: 99.0.4807.0
    Firefox: 95.0
    Safari: 15.2

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions