存根 process.exit 开玩笑 [英] stubbing process.exit with jest

查看:29
本文介绍了存根 process.exit 开玩笑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码可以做类似的事情

I have code that does something like

 function myFunc(condition){
  if(condition){
    process.exit(ERROR_CODE)
  }
 }

我如何在 Jest 中测试这个?用 jest.fn() 覆盖 process 中的 exit 并在测试后返回它不起作用,因为进程退出了

How can I test this in Jest? Overwriting exit in process with jest.fn() and returning it back after the test doesn't work, since the process exits

推荐答案

该线程中的其他建议会导致我这边出现错误,任何带有 process.exit 的测试都会无限期地运行.以下选项在 TypeScript 上对我有用,但它也应该在 JavaScript 上工作:

The other suggestions in this thread would cause errors on my end, where any tests with process.exit would run indefinitely. The following option worked for me on TypeScript, but it should work on JavaScript as well:

const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {});
myFunc(condition);
expect(mockExit).toHaveBeenCalledWith(ERROR_CODE);

问题在于,简单地使用 spyOn 意味着仍会调用原始的 process.exit() 函数,从而结束进程线程并挂起测试.最后使用 mockImplementation 将函数体替换为提供的函数(在我的示例中为空).

The catch is that simply using spyOn meant that the original process.exit() function was still called, ending the process thread and hanging tests. Using mockImplementation at the end replaces the function body with the provided function (which is empty in my example).

这个技巧对于打印到标准输出的测试也很有用.例如:

This trick is also useful for tests that print to, say, stdout. For example:

const println = (text: string) => { process.stdout.write(text + '
'); };
const mockStdout = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});
println('This is a text.');
expect(mockStdout).toHaveBeenCalledWith('This is a text.
');

这将让您测试打印的值,并具有不会用随机换行符弄乱 CLI 控制台输出的额外好处.

This will let you test printed values, and have the added benefit of not messing up CLI console output with random linebreaks.

请注意:与任何jest.spyOn"调用一样,无论是否使用模拟实现,您都需要稍后恢复它,以避免挥之不去的模拟产生奇怪的副作用.因此,请记住在当前测试用例的末尾调用以下两个函数:

Just one note: As with any "jest.spyOn" call, regardless of using mock implementation or not, you need to restore it later on in order to avoid weird side-effects of lingering mocks. As such, remember to call the two following functions at the end of the current test case:

mockExit.mockRestore()
mockStdout.mockRestore()

这篇关于存根 process.exit 开玩笑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆