0

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
  });
});

demo on codesandbox

I wonder how to test temp.js. Thanks for your help!

enter image description here

Koko
  • 1
  • Update `process.env` before `import { temp } from "./temp";` – hoangdv Aug 22 '21 at 13:16
  • Does this answer your question? [Using .env files for unit testing with jest](https://stackoverflow.com/questions/50259025/using-env-files-for-unit-testing-with-jest) – skyboyer Aug 22 '21 at 21:20

0 Answers0