How to mock a module multiple times? #1255
-
In my source code, I use the Here is my source code: import { cosmiconfig } from 'cosmiconfig';
import TypeScriptLoader from 'cosmiconfig-typescript-loader';
const explorer = cosmiconfig(CONFIGURATION_MODULE_NAME, {
searchPlaces: SEARCH_PLACES,
loaders: {
'.ts': TypeScriptLoader(),
},
});
const result = await explorer.search(); I want to mock this What's the correct way of doing so? For example, for checking upon import { describe, it, expect, afterEach, vi } from 'vitest';
vi.mock('cosmicocnfig', () => {
return {
cosmiconfig: vi.fn(() => {
return {
search: () => Promise.resolve(null),
};
}),
};
}); But now I also want to test when |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 11 replies
-
You can import it and change the returned value: import { cosmiconfig } from 'cosmiconfig'
vi.mocked(cosmiconfig).mockReturnValue({
search: () => Promise.reject(null)
})
|
Beta Was this translation helpful? Give feedback.
-
I know I have a flaw in line 8 in the snippet I've provided. I fixed the flaw but the issue persists |
Beta Was this translation helpful? Give feedback.
-
Can confirm the answer was indeed provided, and I have some irrelevant issue |
Beta Was this translation helpful? Give feedback.
-
The following works for me. myFunction.js
myFunction.spec.js
|
Beta Was this translation helpful? Give feedback.
-
See also #4124 |
Beta Was this translation helpful? Give feedback.
You can import it and change the returned value:
vi.mocked
is just a typehint, btw. It's noop.