How to mock optional import in vitest #6344
-
Hello, I have a constants.js file that imports a configuration .js file for local use only. This file is not available when running unit tests on a server or in the production build. However, Vitest seems to fail when the import is run and expects the file to be there. How do I get around this? Here is what I have currently tried: ./src/static/constants.js ...
let local;
let configModule;
if (!IS_PROD) {
try {
configModule = await import("./local_config.js");
local.config = configModule.default;
configModule = await import("./local_settings.js");
local.settings= configModule.default;
} catch (error) {
console.warn(error);
}
} ./setup.js import { vi, beforeAll } from 'vitest';
beforeAll(() => {
vi.mock("./src/static/local_config.js", () => undefined);
}); ./vitest.config.js import { defineConfig } from "vite";
export default defineConfig({
esbuild: {
supported: {
"top-level-await": true
},
},
test: {
environment: "jsdom",
globals: true,
setupFiles: [ "./setup.js" ],
},
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
You need to specify a fallback in the config because the error is controlled by Vite, not Vitest: https://vitest.dev/guide/mocking.html#virtual-modules
|
Beta Was this translation helpful? Give feedback.
You need to specify a fallback in the config because the error is controlled by Vite, not Vitest:
https://vitest.dev/guide/mocking.html#virtual-modules