Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically imported mocks are initiated multiple times #1563

Closed
6 tasks done
christian-bromann opened this issue Jun 28, 2022 · 1 comment · Fixed by #1726
Closed
6 tasks done

Dynamically imported mocks are initiated multiple times #1563

christian-bromann opened this issue Jun 28, 2022 · 1 comment · Fixed by #1726

Comments

@christian-bromann
Copy link
Contributor

Describe the bug

Given a module that imports a package dynamically, e.g.:

export default async () => {
  const id = 'a-vitest-test-modulea';
  return (await import(id)).default();
};

If I define a-vitest-test-modulea as a mock via:

vi.mock('a-vitest-test-modulea', () => {
  console.log('INITIALIZE MOCK');
  return {
    default: vi.fn().mockReturnValue('I am mocked'),
  };
});

then the mock gets initialised multiple times - one time when my actual source file imports it and the other when my test imports it so I can make assertions - which makes it impossible to run e.g. toBeCalledTimes assertions. This is working in Jest as expected.

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-payj4m?file=src%2Findex.ts,test%2Fbasic.test.ts&initialPath=__vitest__

System Info

System:
    OS: Linux 5.16 Ubuntu 20.04.4 LTS (Focal Fossa)
    CPU: (16) x64 AMD EPYC 7B13
    Memory: 31.36 GB / 62.80 GB
    Container: Yes
    Shell: 5.8 - /usr/bin/zsh
  Binaries:
    Node: 18.4.0 - ~/.nvm/versions/node/v18.4.0/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v18.4.0/bin/yarn
    npm: 8.12.1 - ~/.nvm/versions/node/v18.4.0/bin/npm
  Browsers:
    Chrome: 101.0.4951.64
  npmPackages:
    vitest: ^0.16.0 => 0.16.0

Used Package Manager

npm

Validations

@christian-bromann
Copy link
Contributor Author

Note: when modifying the module to import a string rather than a variable, the behavior is expected:

export default async () => {
  // this way it works
  return (await import('a-vitest-test-modulea')).default();
  // this way it doesn't
  const id = 'a-vitest-test-modulea';
  return (await import(id)).default();
};

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants