由于jest
我无法测试commander
导致进程退出的模块功能。
例如,如果我传递了--help
选项或无效参数-x
(见下文)process.exit
,或者process.stdout.write
没有被调用,因为他们应该查看commander
源代码。
import {Command} from "commander";
let mockExit: jest.SpyInstance;
let mockStdout: jest.SpyInstance;
beforeAll(() => {
mockExit = jest.spyOn(process, "exit").mockImplementation();
mockStdout = jest.spyOn(process.stdout, "write").mockImplementation();
});
afterAll(() => {
mockExit.mockRestore();
mockStdout.mockRestore();
});
test("Ask for help", () => {
// Setup
const save = JSON.parse(JSON.stringify(process.argv));
process.argv = ["--help"]; // Same setting it to "-x"
const program = new Command();
program
.option("-v, --verbose [level]", "verbose level")
.parse(process.argv);
expect(mockExit).toBeCalled();
// expect(mockStdout).toBeCalled();
// Cleanup
process.argv = save;
});
奇怪的是,从其他测试的行为来看,process.argv
在这一次之后并没有恢复。测试在打字稿中并通过ts-jest
. 有任何想法吗?谢谢!