如何使用Jest模拟测试Node.js CLI? [英] How to mock test a Node.js CLI with Jest?
问题描述
我一开始就很困惑,只是需要CLI并捕获其输出.我尝试了两种方法,但是都无法使用.
I'm stuck at the very beginning, simply requiring the CLI and capturing its output. I've tried two methods but both don't work.
这是我的cli.js:
This is my cli.js:
#!/usr/bin/env node
console.log('Testing...');
process.exit(0);
这是我的cli.test.js:
And this my cli.test.js:
test('Attempt 1', () => {
let stdout = require("test-console").stdout;
let output = stdout.inspectSync(function() {
require('./cli.js');
});
expect(output).toBe('Testing...');
});
test('Attempt 2', () => {
console.log = jest.fn();
require('./cli.js');
expect(console.log.calls).toBe(['Testing...']);
});
实际运行哪个测试并不重要,输出始终为:
Doesn't really matter which test is actually being run, the output is always:
$ jest
RUNS bin/cli.test.js
Done in 3.10s.
推荐答案
Node.js CLI应用程序与其他应用程序没有什么不同,除了它们依赖于环境.他们应该广泛使用 process
成员,例如:
Node.js CLI applications are no different to other applications except their reliance on environment. They are expected to extensively use process
members, e.g.:
-
process.stdin
-
process.stdout
-
process.argv
-
process.exit
如果使用了其中任何一种,则应对其进行相应的模拟和测试.
If any of these things are used, they should be mocked and tested accordingly.
由于直接调用 console.log
进行输出,因此可以直接监视它,尽管也可以使用诸如 test-console
之类的帮助程序包.
Since console.log
is called directly for output, there's no problem to spy on it directly, although helper packages like test-console
can be used too.
在这种情况下,在导入的文件中调用了 process.exit(0)
,因此规格文件提前退出,而下一个 Done
输出来自父进程.它应该被存根.抛出错误是必要的,以便停止执行代码-模仿正常行为:
In this case process.exit(0)
is called in imported file, so spec file early exits, and next Done
output is from parent process. It should be stubbed. Throwing the error is necessary so that code execution is stopped - to mimic the normal behavior:
test('Attempt 2', () => {
const spy = jest.spyOn(console, 'log');
jest.spyOn(process, 'exit').mockImplementationOnce(() => {
throw new Error('process.exit() was called.')
});
expect(() => {
require('./cli.js');
}).toThrow('process.exit() was called.');
expect(spy.mock.calls).toEqual([['Testing...']]);
expect(process.exit).toHaveBeenCalledWith(0);
});
这篇关于如何使用Jest模拟测试Node.js CLI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!