Sometimes, we want to mock console when it is used by a third-party library with Jest.
In this article, we’ll look at how to mock console when it is used by a third-party library with Jest.
How to mock console when it is used by a third-party library with Jest?
To mock console when it is used by a third-party library with Jest, we can set the global.console
property to our own mock object.
For instance, we write:
global.console = {
warn: jest.fn()
}
expect(console.warn).toBeCalled()
to set global.console
to an object that mocks the console.warn
method by setting warn
to jest.fn
.
Then we check that console.warn
is called with expect(console.warn).toBeCalled()
.
We can also use jest.spyOn
to mock console.warn
with
jest.spyOn(global.console, 'warn')
since Jest 19.0.0.
Conclusion
To mock console when it is used by a third-party library with Jest, we can set the global.console
property to our own mock object.