【发布时间】:2021-04-02 15:27:48
【问题描述】:
我有一个 Node.js 应用程序,其中index.js 对类 Unix 和 Windows 平台有不同的导出。
import os from "os";
function throwNotSupportedError() {
throw new Error("Platform not supported.");
}
console.log(os.platform());
switch (os.platform()) {
case "darwin":
case "linux":
module.exports = {
foo: require("./unix/foo"),
bar: require("./unix/bar")
};
break;
case "win32":
module.exports = {
foo: require("./win32/foo"),
bar: require("./win32/bar")
};
break;
default:
throwNotSupportedError();
}
我正在尝试使用如下所示的单元测试来覆盖此文件:
import os from "os";
jest.mock("os");
describe("Linux platform", () => {
test("has `foo` and `bar` methods on Linux platform", () => {
os.platform.mockImplementation(() => "linux");
const app = require("../src");
expect(app.foo).toBeTruthy();
expect(app.bar).toBeTruthy();
});
});
describe("Windows platform", () => {
test("has `foo` and `bar` methods on Windows platform", () => {
os.platform.mockImplementation(() => "win32");
const app = require("../src");
expect(app.foo).toBeTruthy();
expect(app.bar).toBeTruthy();
});
});
问题是os.platform.mockImplementation(() => "win32"); 有效,但console.log(os.platform()); 仍然显示linux,即使我在每个测试用例const app = require("../src"); 中导入应用程序。
我的错误在哪里以及如何解决?
【问题讨论】:
标签: javascript node.js unit-testing jestjs