Skip to content
Advertisement

Vitest mock modules function in only one test and use the actual function in others

The following is an abstraction of my problem and thus does not make too much sense:

Given I have a simple utility callMethodIf that’s returning the return of another imported method (blackbox).

~~/utils/call-method-if.js:

JavaScript

~~/utils/blackbox.js:

JavaScript

How would I run one test case which calls the actual implementation of blackbox() and another one where I mock the return value of blackbox()?

I tried to do it that way:

JavaScript

Both tests work if I run only one of them, but they don’t work when combined.

Running vi.clearAllMocks() or vi.resetAllMocks() don’t help.

Defining a global mock and overwriting it in my first test doesn’t work either:

JavaScript

Advertisement

Answer

Okay, after lots of trial and error I finally got it to work. I can’t really tell why my previous tries do not work tough.

Working solution:

JavaScript

When using TypeScript consider typing the importActual() return like that:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement