Skip to content Skip to sidebar Skip to footer

How Do I Test A Jest Console.log

I'm using create-react-app and trying to write a jest test that checks the output of a console.log. My function to test is: export const log = logMsg => console.log(logMsg); My

Solution 1:

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

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.

Solution 2:

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

Solution 3:

Another option is to save off a reference to the original log, replace with a jest mock for each test, and restore after all the tests have finished. This has a slight benefit to not polluting the test output and still being able to use the original log method for debugging purposes.

describe("Some logging behavior", () => {
  const log = console.log; // save original console.log functionbeforeEach(() => {
    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 logexpect(console.log).not.toHaveBeenCalled();
  });
  test("some log", () => {
    // TODO: test something that should logexpect(console.log).toHaveBeenCalled();
    const message = console.log.mock.calls[0][0]; // get log messageexpect(message).toEqual(expect.stringContaining('something')); // assert on the message contentlog(message); // actually log out what the mock was called with
  });
});

Solution 4:

I would consider toHaveBeenCalledWith or any other of the methods that jest offers for checking mock calls (the ones that start with toHaveBeenCalled).

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

Post a Comment for "How Do I Test A Jest Console.log"