Categories
JavaScript Answers

How to test a Jest console.log with Jest and JavaScript?

Spread the love

To test a Jest console.log with Jest and JavaScript, we can spy on the console.log method.

For instance, we write

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

  console.log("hello");

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

to call jest.spyOn to spy on the console.log method.

Then we call console.log with the value we want to check.

Next we check the value console.log is called with with toHaveBeenCalledWith.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *