Search code examples
unit-testingtestingjestjsvitevitest

How to do manual mocks in Vitest?


I'm basically trying to mock an external module in the same way for all my vitest tests, and it's surprisingly not trivial. In Jest, I would just create a __mocks__ folder at the root, and it appears vitest is maybe supposed to support this, but I can't get it to work. Anybody figured out this (seemingly very basic) use case?

Tried creating a __mocks__ folder at the root, tried doing a global mock in vite.config.ts. I want to create one mock that works for all tests


Solution

  • Add a setup file to your config:

    test: {
      setupFiles: ['./vitest.setup.ts'],
    }
    

    Then you can mock your modules inside the test file, but make sure to prefix module names with node: when mocking node modules. It took me a while to figure this out... and it's not in the docs. This helped me