Jest 会吞下 console.log 语句吗?有没有办法改变这个?
Posted
技术标签:
【中文标题】Jest 会吞下 console.log 语句吗?有没有办法改变这个?【英文标题】:Does Jest swallow console.log statements? Is there a way to change this? 【发布时间】:2017-04-26 21:03:05 【问题描述】:Jest 会吞下console.log
输出吗?
// __tests__/log.test.js
it('logs', () =>
console.log('hey') // expect to see "hey" printed in terminal
)
// terminal output
$ jest --forceExit
PASS __tests__/log.test.js
✓ logs (1ms) # where's "hey"?
我关心的主要原因是我正在编写一些异步 beforeAll
和 afterAll
的东西,并且我想使用 console.log 语句来调试事件的顺序。
【问题讨论】:
--useStderr
为我工作的版本 v22.4.2
jestjs.io/docs/en/cli.html#--usestderr jestjs.io/docs/en/cli.html#options
这能回答你的问题吗? Console.log statements output nothing at all in Jest
【参考方案1】:
这似乎是ongoing issue。
使用 Node 10.7.0 和 Jest 23.4.1,将 verbose: false
添加到 jest 配置 (per this suggestion) 对我有用。
编辑
现在我已经去了 Jest 23.6,根据 Tamlyn 的回答,我还需要将 TERM=dumb
作为环境变量传递。
【讨论】:
【参考方案2】:更新:这个问题应该被修复as of Jest 24。
另一个解决current bug 影响--watch
模式下测试的部分解决方案是将TERM=dumb
作为环境变量传递。
TERM=dumb jest --watch
这样做的代价很小,因为它不再在每次测试运行之前清除控制台,因此您必须滚动才能看到结果。
【讨论】:
【参考方案3】:问题是我使用的是jest --forceExit
。 Jest 的日志记录模型保存所有日志并在以后将它们吐出。 --forceExit
导致进程在到达 spit-out-logs 点之前退出。
【讨论】:
我在不使用--forceExit
的情况下遇到了这个问题。 =/ 有什么建议吗?
我没有使用forceExit
设置,我仍然看到开玩笑的控制台语句。
不确定你们都在哪个版本的节点上,但我有同样的问题,这似乎是节点 7.3 上的一个已知问题。 github.com/facebook/jest/issues/2441
--bail, -b
选项也会发生
有趣的发现,谢谢!作为删除 forceExit 的替代方法,您还可以使用 await new Promise( resolve => setTimeout( resolve, 100 ) );
之类的内容跟进您的 console.log(只要您在受支持的 Node 版本上使用异步函数)【参考方案4】:
我找到了解决方法,尽管很遗憾TERM=dumb
、verbose: false
和升级到版本 24 都不起作用(我在 24.9)。只需在控制台上窥探,您就可以看到结果。用这个设置它:
const consoleSpy = jest.spyOn(console, 'log')
然后在运行测试后查看调用:
consoleSpy.mock.calls[0][0]
【讨论】:
【参考方案5】:尝试将--verbose
添加到 Jest 参数中。
这对我有用。
【讨论】:
以上是关于Jest 会吞下 console.log 语句吗?有没有办法改变这个?的主要内容,如果未能解决你的问题,请参考以下文章