Categories
JavaScript Answers

How to mock console when it is used by a third-party-library with Jest and JavaScript?

Spread the love

Sometimes, we want to mock console when it is used by a third-party-library with Jest and JavaScript.

In this article, we’ll look at how to mock console when it is used by a third-party-library with Jest and JavaScript.

How to mock console when it is used by a third-party-library with Jest and JavaScript?

To mock console when it is used by a third-party-library with Jest and JavaScript, we call the jest.spyOn method.

For instance, we write

const consoleWarnMock = jest.spyOn(console, 'warn').mockImplementation();

to mock the console.warn method with the spyOn method in our test.

And then we call mockImplementation to return a mocked version of console.warn.

When we’re done with the test, then we call

consoleWarnMock.mockRestore();

to restore the original console.warn method.

Conclusion

To mock console when it is used by a third-party-library with Jest and JavaScript, we call the jest.spyOn method.

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 *