【发布时间】:2019-01-29 09:05:23
【问题描述】:
我在一个文件中有一个私有函数,它使用console.log。我想在我的Jest 测试中检查console.log 是否确实运行。因此要访问私有函数,我使用rewire。
我有以下文件:
// a.js
function b() {
console.log('c');
}
我有以下测试文件,其中我使用方法suggested here 将console.log 替换为Jest 模拟函数,并使用method here 确保在rewire 之前进行替换:
// a.test.js
global.console = {
log: jest.fn(),
};
const rewire = require('rewire');
const a = rewire('./a');
test('b', () => {
a.__get__('b')();
expect(global.console.log).toHaveBeenCalled();
});
然而,当我运行测试时,我得到:
● Test suite failed to run
logger must implement log, warn and error methods
如果我改用以下测试代码:
// a.test.js
const rewire = require('rewire');
const a = rewire('./a');
a.__set__('console', {
log: jest.fn(),
});
test('b', () => {
a.__get__('b')();
expect(global.console.log).toHaveBeenCalled();
});
我收到以下错误:
expect(jest.fn())[.not].toHaveBeenCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound log]
在私有函数中使用 console.log 时,有什么办法可以窥探到吗?
【问题讨论】:
标签: javascript module jestjs private console.log