如何测试jest console.log

Hel*_*rld 14 javascript reactjs jestjs

我正在使用create-react-app并尝试编写一个检查console.log输出的jest测试

我的测试功能是:

export const log = logMsg => console.log(logMsg);
Run Code Online (Sandbox Code Playgroud)

我的测试是:

it('console.log the text "hello"', () => {
  console.log = jest.fn('hello');
  expect(logMsg).toBe('hello');
});
Run Code Online (Sandbox Code Playgroud)

这是我的错误

 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.
Run Code Online (Sandbox Code Playgroud)

小智 39

或者你可以这样做:

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

  console.log('hello');

  expect(consoleSpy).toHaveBeenCalledWith('hello');
});
Run Code Online (Sandbox Code Playgroud)

  • 为了向其他人澄清 @ProLoser 的建议,您可以使用 `jest.spyOn(console, 'log').mockImplementation(() => {})` 来防止日志混乱您的测试日志,如果您愿意的话。 (4认同)
  • 这是最安全且副作用最小的答案,我推荐它而不是其他解决方案。您也可以使用间谍来静音默认行为,并且玩笑将确保在测试结束时正确恢复所有内容(与大多数其他答案不同)。这也是最简洁、最组合的方法。 (3认同)

JeB*_*JeB 17

如果你想检查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');
});
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多.


fil*_*oxo 5

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

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

Run Code Online (Sandbox Code Playgroud)

  • 唯一适用于隔离测试的解决方案。这应该是公认的答案,因为其他解决方案会对已记录的内容给出错误的否定响应 (3认同)