将 rewire 与 Jest 一起使用,以监视私有函数中使用的 console.log
Use rewire with Jest, to spy on console.log used in a private function
我在一个文件中有一个私有函数,它使用 console.log
。我想在我的 Jest test. Therefore to access the private function, I use rewire.
中检查 console.log
确实 运行
我有以下文件:
// a.js
function b() {
console.log('c');
}
我有以下测试文件,我在其中使用方法 to replace console.log
with a Jest mock function, and the 确保在 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
吗?
跟踪您提供的模拟 __set__
并直接对其断言:
const rewire = require('rewire');
const a = rewire('./a');
const logMock = jest.fn(
(...args) => console.log('logMock called with', ...args)
);
a.__set__('console', {
log: logMock,
});
test('b', () => {
a.__get__('b')();
expect(logMock).toHaveBeenCalled();
});
我在一个文件中有一个私有函数,它使用 console.log
。我想在我的 Jest test. Therefore to access the private function, I use rewire.
console.log
确实 运行
我有以下文件:
// a.js
function b() {
console.log('c');
}
我有以下测试文件,我在其中使用方法 console.log
with a Jest mock function, and the 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
吗?
跟踪您提供的模拟 __set__
并直接对其断言:
const rewire = require('rewire');
const a = rewire('./a');
const logMock = jest.fn(
(...args) => console.log('logMock called with', ...args)
);
a.__set__('console', {
log: logMock,
});
test('b', () => {
a.__get__('b')();
expect(logMock).toHaveBeenCalled();
});