Note: this way only works with Vanilla Vue and doesn't work in Nuxt (I tested this), if your project is Nuxt 3, you can read this post to setup Setting Up and Using Vitest in Nuxt 3 to write unit tests
I seemed depressed and hopeless when I tried to use import.meta.env in Jest to test. But all thing I receive is a message:
TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'
But If you are having this problem and you are reading this post, happy guy, you are helped.
At the start, I use the combo Jest + Vite + typescript + ts-jest
After a long time to find the solution, I found
https://github.com/kulshekhar/ts-jest/issues/1174#issuecomment-1507885348
The solution of terwer is used babel-jest instead of ts-jest
Now, We will do it step by step.
Install the necessary packages:
npm i --save-dev babel-jest @babel/core @babel/preset-env
npm i --save-dev @babel/preset-typescript
npm i --save-dev babel-plugin-transform-vite-meta-env
Install dotenv package to load the Vite environment variable into .env
npm i --save-dev dotenv
module.exports = {
presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript"],
plugins: ["babel-plugin-transform-vite-meta-env"],
}
Create a setupTests.ts file in the folder src/tests (or anywhere you want), this file will be called in jest.config.cjs below
import dotenv from 'dotenv';
dotenv.config({ path: '.env' });
module.exports = {
testEnvironment: "node",
setupFilesAfterEnv: ['./src/tests/setupTests.ts'],
}
{
"scripts": {
...
"test": "jest"
},
}
I have a class that contains global variables like this:
// env.ts
export default class ENV{
static server = import.meta.env.VITE_SERVER_DB;
static API_AUTH = ENV.server + '/auth';
static API_NOTIFICATION = ENV.server + '/notification';
static API_GROUP = ENV.server + '/group';
static realTimeLive = 30;
}
Now, I want to create a rule that the value of all variables must be lowercase. If any variable has the value containing any character in upper case, the testing will fail. I code like this:
import ENV from "../env";
describe("Unit test", ()=>{
test("Check all environment variables have value in lowercase", async () => {
const variableNames = Object.keys(ENV);
const uppercaseVariables = variableNames.filter(name => (ENV as any)[name].toString() !== (ENV as any)[name].toString().toLowerCase());
expect(uppercaseVariables).toEqual([]); // Expect no variable value to contain uppercase characters
});
});
Output:
Success case:
PASS src/tests/unit.test.ts
Unit test
√ Check all environment variables have value in lowercase (3 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.779 s, estimated 1 s
Ran all test suites.
Failed case (if I change API_AUTH = ENV.server + '/Auth'; ):
FAIL src/tests/unit.test.ts
Unit test
× Check all environment variables have value in lowercase (6 ms)
● Unit test › Check all environment variables have value in lowercase
expect(received).toEqual(expected) // deep equality
- Expected - 1
+ Received + 3
- Array []
+ Array [
+ "API_AUTH",
+ ]
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.814 s, estimated 1 s
Ran all test suites.
Hope you will success