Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to test a Jest console.log with Jest and JavaScript.

In this article, we’ll look at how to test a Jest console.log with Jest and JavaScript.

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

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.

Conclusion

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

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.