How to use Jest with jsdom to test console.log?

I just tune in to Jest, and I have successfully written unit tests that test the DOM. I have a library that picks up elements on the screen, so I can check everything perfectly. In some cases, instead of throwing an error, my library spits out console.warn or console.log . Can I use Jest to verify that these console messages are occurring?

+14
source share
2 answers

You can install console.log with such a spy:

 global.console = { warn: jest.fn(), log: jest.fn() } // run your code expect(global.console.log).toHaveBeenCalledWith('test') 

Since your test file runs in a separate thread, you do not need to reset console to the original methods

+35
source

Suppose you want to test such a function by typing a message:

 function sayHello () { console.log('Hello!') } 

You can use the jest.spyOn function to change the behavior of the console.log function.

 describe('sayHello prints "Hello!"', () => { const log = jest.spyOn(global.console, 'log') sayHello() expect(log).toHaveBeenCalledWith('Hello!') }) 

OR you can override the console object and add a key with the value jest.fn , for example:

 describe('sayHello prints "Hello!"', () => { const log = jest.fn() global.console = { log } sayHello() expect(log).toHaveBeenCalledWith('Hello!') } 
+1
source

Source: https://habr.com/ru/post/1268506/


All Articles