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();
);





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







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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ