Skip to content

Instantly share code, notes, and snippets.

@CarmeloRicarte
Created December 10, 2022 13:20
Show Gist options
  • Save CarmeloRicarte/df05e8c303c0ea27ec9a8c8a663f8ce8 to your computer and use it in GitHub Desktop.
Save CarmeloRicarte/df05e8c303c0ea27ec9a8c8a663f8ce8 to your computer and use it in GitHub Desktop.
Use ENV in testing with Vite

Use ENV in testing with Vite

  1. Install dotenv package as dev depencency.
  2. 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.
  3. Create a helper function that will return all env:
export const getEnvironments = () => {
  import.meta.env;
  return {
    ...import.meta.env,
  };
};
  1. 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.

  1. Add setupTests.ts to include property in tsconfig.json file:
"include": ["src", "./setupTests.ts"],
  1. 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"],
  },
});
  1. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment