In our team's project, I encountered a problem that hasn't been solved yet.
It is about unit test. I simplified the code like below. Also add an online demo below
// this is temp.js
// when run temp.test.js, b is assigned undefined
// because process.env.TEMP is undefined at that time
const b = `${process.env.TEMP}`;
// console.log(process.env.TEMP); // is undefined
export function temp(a) {
// if b is defined in here, process.env.TEMP works
// const b = `${process.env.TEMP}`;
return b;
}
// export other function, also use b
// this is temp.test.js
import { temp } from "./temp";
process.env = {
TEMP: "temp"
};
describe("temp", () => {
test("test temp", () => {
// console.log("temp test.js: ", process.env.TEMP); // is temp
expect(temp()).toBe("undefined"); // pass
// expect(temp()).toBe("temp"); // not pass, hope it can works
});
});
I wonder how to test temp.js
. Thanks for your help!