如何测试jest console.log

时间:2018-03-04 13:45:32

标签: javascript reactjs jestjs

我正在使用create-react-app并尝试编写一个检查控制台输出的jest测试。日志

我的测试功能是:

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.

4 个答案:

答案 0 :(得分:10)

如果您想检查console.log是否收到了正确的参数(您传入的参数),则应该检查mock的{​​{1}}。 您还必须调用jest.fn()函数,否则永远不会调用log

console.log

了解更多here

答案 1 :(得分:4)

或者您可以这样做:

it('calls console.log with "hello"', () => {
  const consoleSpy = jest.spyOn(console, 'log');

  console.log('hello');

  expect(consoleSpy).toHaveBeenCalledWith('hello');
});

答案 2 :(得分:2)

另一种选择是保存对原始日志的引用,为每个测试替换一个jest模拟,并在所有测试完成后恢复。这对不污染测试输出以及仍然能够使用原始日志方法进行调试有一点好处。

describe("Some logging behavior", () => {
  const log = console.log; // save original console.log function
  beforeEach(() => {
    console.log = jest.fn(); // create a new mock function for each test
  });
  afterAll(() => {
    console.log = log; // restore original console.log after all tests
  });
  test("no log", () => {
    // TODO: test something that should not log
    expect(console.log).not.toHaveBeenCalled();
  });
  test("some log", () => {
    // TODO: test something that should log
    expect(console.log).toHaveBeenCalled();
    const message = console.log.mock.calls[0][0]; // get log message
    expect(message).toEqual(expect.stringContaining('something')); // assert on the message content
    log(message); // actually log out what the mock was called with
  });
});

答案 3 :(得分:1)

我会考虑使用toHaveBeenCalledWith或开玩笑提供的其他任何方法来检查模拟调用(the ones that start with toHaveBeenCalled)。

it('console.log the text "hello"', () => {
  console.log = jest.fn();
  log('hello');
  expect(console.log).toHaveBeenCalledWith('hello');
});