我正在尝试模拟 console.warn/error 但我做不到。我使用了一个第三方库,它在里面调用了 console.warn。我需要测试它是否被调用。在我的测试用例中,我试图 stub console.warn 但它没有帮助。之后我尝试手动模拟控制台,但也没有成功。
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
。
最佳答案
您必须使用global
来访问全局上下文中的对象
global.console = {warn: jest.fn()}
expect(console.warn).toBeCalled()
或使用19.0.0
中添加的jest.spyOn
jest.spyOn(global.console, 'warn')
关于javascript - Jest : how to mock console when it is used by a third-party-library?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223963/