我有electron-util.js
个文件,我不想用测试进行介绍:
const isElectron = "electron" in process.versions;
const isUsingAsar =
isElectron &&
process.mainModule &&
process.mainModule.filename.includes("app.asar");
export const fixPathForAsarUnpack = path =>
isUsingAsar ? path.replace("app.asar", "app.asar.unpacked") : path;
为了测试fixPathForAsarUnpack
方法,我需要从versions
模拟mainModule
和process
。我试图这样做:
import { fixPathForAsarUnpack } from "../src/electron-util";
test("fixes path for Electron", () => {
process.versions = {
electron: "0.0.0",
mainModule: {
filename: "/app.asar/index.html"
}
};
const path =
"/Users/relix/My.app/Contents/Resources/app.asar/node_modules/foo/binary";
expect(fixPathForAsarUnpack(path)).toBe(
"/Users/relix/My.app/Contents/Resources/app.asar.unpack/node_modules/foo/binary"
);
});
但是会引发错误:
● fixes path for Electron
TypeError: Cannot assign to read only property 'versions' of object '[object process]'
4 |
5 | test("fixes path for Electron", () => {
> 6 | process.versions = {
| ^
7 | electron: "0.0.0",
8 | mainModule: {
9 | filename:
at Object.<anonymous>.test (__test__/electron-util.test.js:6:3)
我在做什么错,我该如何模拟process
对象?
答案 0 :(得分:1)
您应该以这种方式模拟该过程:
const originalProcess = process
global.proces = {...originalProcess, version: "your code here"}
// do the test
// ...
// restore the original process object for next tests
global.process = originalProcess