- Install dotenv package as dev depencency.
- Create .env.test at root of your project, with the same environment variables that you have in your .env file. Then, add it to .gitignore file.
- Create a helper function that will return all env:
export const getEnvironments = () => {
import.meta.env;
return {
...import.meta.env,
};
};
- Create a file setupTests.ts at root of your project, adding the following code:
import { vi } from "vitest";
/* Mocking the getEnvironments function to return the process.env object. */
require("dotenv").config({
path: ".env.test",
});
vi.mock("./src/helpers/getEnvironments", () => ({
getEnvironments: () => ({
...process.env,
}),
}));
This code will return the environments variables that you have in .env.test as a process.env, that are en env variables that are using for testing.
- Add setupTests.ts to include property in tsconfig.json file:
"include": ["src", "./setupTests.ts"],
- In vite.contig.ts, add setupFiles property inside test object of defineConfig with the route of setupTests.ts file:
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: "jsdom",
setupFiles: ["./setupTests.ts"],
},
});
- In files that you was using
ìmport.meta.env
, call to getEnvironments helper and destructure variables that you need:
const { VITE_NAME_OF_VARIABLE } = getEnvironments();
ann then replace ìmport.meta.env
by the name of variable VITE_NAME_OF_VARIABLE
.