我如何测试一个玩笑的console.log [英] How do I test a jest console.log

查看:43
本文介绍了我如何测试一个玩笑的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()中的mock.
您还必须调用您的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆