How to do manual mocks in Vitest?
Asked Answered
B

1

10

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

Buzzell answered 10/5, 2023 at 0:18 Comment(4)
Given the documentation at vitest.dev/guide/mocking.html#modules, what specifically have you tried, what is not working, and what is the specific minimal reproducible example that you can share?Ralina
Did you get anywhere? I'm also trying this and can't get it to work at all!Gymnastic
Looks like you can go one of two ways, according to the docs (vitest.dev/api/vi.html#vi-mock): 1. add a __mocks__ folder at the root, but make sure to add vi.mock('module'); in the test file or 2. add a test set up file whih handles your mocks and then add it to your vitest config in the "setupFiles" array vitest.dev/config/#setupfiles. From the docs: ...if you don't call vi.mock, modules are not mocked automatically. To replicate Jest's automocking behaviour, you can call vi.mock for each required module inside setupFiles.Brae
@ChristopherBorchert why the docs do not provide an example is beyond meSubtitle
M
2

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

Moravia answered 14/4 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.