我如何测试一个笑话 console.log [英] How do I test a jest console.log
本文介绍了我如何测试一个笑话 console.log的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 create-react-app 并尝试编写一个 jest 测试来检查 console.log
的输出.
I'm using create-react-app and trying to write a jest test that checks the output of a console.log
.
我要测试的功能是:
export const log = logMsg => console.log(logMsg);
我的测试是:
it('console.log the text "hello"', () => {
console.log = jest.fn('hello');
expect(logMsg).toBe('hello');
});
这是我的错误
FAIL src/utils/general.test.js
● console.log the text hello
expect(received).toBe(expected) Expected value to be (using ===): "hello"
Received:
undefined
Difference:
Comparing two different types of values. Expected string but received undefined.
推荐答案
如果您想检查 console.log
是否收到正确的参数(您传入的参数),您应该检查 模拟
你的jest.fn()
.
您还必须调用 log
函数,否则永远不会调用 console.log
:
If you want to check that console.log
received the right parameter (the one that you passed in) you should check mock
of your jest.fn()
.
You also have to invoke your log
function, otherwise console.log
is never invoked:
it('console.log the text "hello"', () => {
console.log = jest.fn();
log('hello');
// The first argument of the first call to the function was 'hello'
expect(console.log.mock.calls[0][0]).toBe('hello');
});
或
it('console.log the text "hello"', () => {
console.log = jest.fn();
log('hello');
// The first argument of the first call to the function was 'hello'
expect(console.log).toHaveBeenCalledWith('hello');
});
在此处阅读更多信息.
这篇关于我如何测试一个笑话 console.log的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文