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

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

问题描述

我有执行类似操作的代码

I have code that does something like

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

如何在Jest中对此进行测试?用jest.fn()覆盖process中的process,然后在测试后将其返回,因为该过程已退出

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).

此技巧对于打印到例如stdout的测试也很有用.例如:

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

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

这将使您能够测试打印的值,并具有不使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天全站免登陆