开玩笑:当第三方库使用控制台时,如何模拟控制台? [英] Jest: how to mock console when it is used by a third-party-library?
问题描述
我正在尝试模拟console.warn/error,但我不能.我使用了一个第三方库,该库在其中调用console.warn.我需要测试它是否被调用.在我的测试案例中,我试图对console.warn进行存根处理,但这没有帮助.之后,我尝试手动模拟控制台,但也没有解决问题.
I am trying to mock console.warn/error but i can't. I use a third-party-library which calls console.warn inside it. I need to test was it called or wasn't. In my test case i was trying to stub console.warn but it didn't help. After that i was trying to mock console manually it didn't work out either.
console.warn = jest.fn();
testSchema('/app/components/Users/UserItem/UserItemContainer.js');
expect(console.warn).toBeCalled();
没用
console.warn = jest.fn();
testSchema('/app/components/Users/UserItem/UserItemContainer.js');
console.warn('error');
expect(console.warn).toBeCalled();
工作了.但是我仍然在终端中看到console.warn node_modules/babel-relay-plugin/lib/getBabelRelayPlugin.js:138
.谁能帮我吗?
did work. But i still see console.warn node_modules/babel-relay-plugin/lib/getBabelRelayPlugin.js:138
in the terminal. Can anyone help me?
推荐答案
您必须使用global
来访问全局上下文中的对象
You have to use global
to access objects in the global context
global.console = {warn: jest.fn()}
expect(console.warn).toBeCalled()
或使用添加在19.0.0
jest.spyOn(global.console, 'warn')
这篇关于开玩笑:当第三方库使用控制台时,如何模拟控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!