Подтвердить что ты не робот

Как проверить jest console.log

Я использую приложение create-react-app и пытаюсь написать тест jest, который проверяет вывод 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.
4b9b3361

Ответ 1

Если вы хотите проверить, что 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');
});

или

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

Подробнее здесь.

Ответ 2

Я хотел бы рассмотреть toHaveBeenCalledWith или любые другие методы, которые предлагает jest для проверки ложных вызовов (те, которые начинаются с toHaveBeenCalled).

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