javascript 我如何测试一个笑话 console.log
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49096093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I test a jest console.log
提问by Hello-World
I'm using create-react-app and trying to write a jest test that checks the output of a console.log
我正在使用 create-react-app 并尝试编写一个检查 console.log 输出的笑话测试
My function to test is:
我要测试的功能是:
export const log = logMsg => console.log(logMsg);
My test is :
我的测试是:
it('console.log the text "hello"', () => {
console.log = jest.fn('hello');
expect(logMsg).toBe('hello');
});
Here is my error
这是我的错误
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.
回答by JeB
If you want to check that console.logreceived the right parameter (the one that you passed in) you should check mockof your jest.fn().
You also have to invoke your logfunction, otherwise console.logis never invoked:
如果您想检查是否console.log收到了正确的参数(您传入的参数),您应该检查mock您的jest.fn().
您还必须调用您的log函数,否则console.log永远不会调用:
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');
});
or
或者
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');
});
Read more here.
在这里阅读更多。
回答by Dozatron
Or you could do it like this:
或者你可以这样做:
it('calls console.log with "hello"', () => {
const consoleSpy = jest.spyOn(console, 'log');
console.log('hello');
expect(consoleSpy).toHaveBeenCalledWith('hello');
});
回答by Simply007
I would consider toHaveBeenCalledWithor any other of the methods that jest offers for checking mock calls (the ones that start with toHaveBeenCalled).
我会考虑toHaveBeenCalledWith或任何其他 jest 提供的用于检查模拟调用的方法(以 toHaveBeenCalled 开头的方法)。
it('console.log the text "hello"', () => {
console.log = jest.fn();
log('hello');
expect(console.log).toHaveBeenCalledWith('hello');
});

