首页 > 解决方案 > 一个函数使用了一个外部变量,如何用 Jest 测试它?

问题描述

在我们团队的项目中,遇到了一个还没有解决的问题。

这是关于单元测试的。我简化了如下代码。还要在下面添加一个在线演示

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

代码沙盒演示

我想知道如何测试temp.js。感谢您的帮助!</p>

在此处输入图像描述

标签: jestjs

解决方案


推荐阅读