Use rewire with Jest, to spy on console.log used in a private function
Use rewire with Jest, to spy on console.log used in a private function
I have a private function in one file, which uses console.log. I want to check that console.log does indeed run, in my Jest test. Therefore to access the private function, I use rewire.
console.log
console.log
I have the following file:
// a.js
function b()
console.log('c');
And I have the following test file, where I use the method suggested here to replace console.log with a Jest mock function, and the method here to ensure the replacement gets made before the rewire:
console.log
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();
);
Yet when I run the test, I get:
● Test suite failed to run
logger must implement log, warn and error methods
And if I use the following test code instead:
// 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();
);
I get the following error:
expect(jest.fn())[.not].toHaveBeenCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound log]
Is there any way at all to spy on console.log when used in a private function?
console.log
1 Answer
1
Keep track of the mock you give __set__ and assert on it directly:
__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();
);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Ah yes thanks, that works great! I'm sure this technique will be useful for doing the same thing with other methods, too.
– Gary
Aug 23 at 16:06