I am trying to migrate my tests from Jest to Vitest. I have a test suite that uses the dotenv package to pull in my .env variables.
I have this in my test suite
beforeAll(async () => {
vi.clearAllMocks();
cleanUpMetadata();
dotenv.config();
controller = new UserController(container.get<UserServiceLocator>(Symbol.for("UserServiceLocator")),
container.get<EmailServiceLocator>(Symbol.for("EmailServiceLocator")));
});
and this is the code in the test that has the undefined variable:
let requestObj = httpMocks.createRequest({
cookies: {
token: jwt.sign({ username: "testusername" }, process.env.JWT_SECRET_KEY!)
}
});
Is there something special to Vitest that I have to do in order to get my .env variables to be accessible?
You can include the dotenv package(if thats what you are using) into the vitest.config.ts file, it will look something like this below:
import { defineConfig } from 'vitest/config';
import { resolve } from 'path';
export default defineConfig({
root: '.',
esbuild: {
tsconfigRaw: '{}',
},
test: {
clearMocks: true,
globals: true,
setupFiles: ['dotenv/config'] //this line,
},
resolve: {
alias: [{ find: '~', replacement: resolve(__dirname, 'src') }],
},
});
For whoever lands here after removing the dotenv lib because Node v20.6.0+ handles .env files automatically, just use the loadEnv function from vite in your vitest.config.ts:
import { loadEnv } from 'vite';
import { defineConfig } from 'vitest/config';
export default defineConfig(({ mode }) => ({
test: {
// mode defines what ".env.{mode}" file to choose if exists
env: loadEnv(mode, process.cwd(), ''),
},
}));
Provided you use a default .env file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With