Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test a jest console.log

I'm using create-react-app and trying to write a jest test that checks the output of a console.log.

My function to test is:

export const log = logMsg => console.log(logMsg); 

My test is :

it('console.log the text "hello"', () => {   console.log = jest.fn('hello');   expect(logMsg).toBe('hello'); }); 

Here is my error

 FAIL  src/utils/general.test.js   ● console.log the text hello      expect(received).toBe(expected)    Expected value to be (using ===):      "hello"     Received:       undefined     Difference:       Comparing two different types of values. Expected string but received undefined. 
like image 925
Hello-World Avatar asked Mar 04 '18 13:03

Hello-World


People also ask

Does console log work in Jest?

To fix console. log statements output nothing in Jest, we can set the silent option to false . to set silent to false given that test is a script in package. json that runs jest .

How do you run a Jest test?

In order to run a specific test, you'll need to use the jest command. npm test will not work. To access jest directly on the command line, install it via npm i -g jest-cli or yarn global add jest-cli . Then simply run your specific test with jest bar.


2 Answers

If you want to check that console.log received the right parameter (the one that you passed in) you should check mock of your jest.fn().
You also have to invoke your log function, otherwise console.log is never invoked:

it('console.log the text "hello"', () => {   console.log = jest.fn();   log('hello');   // The first argument of the first call to the function was 'hello'   expect(console.log.mock.calls[0][0]).toBe('hello'); }); 

or

it('console.log the text "hello"', () => {   console.log = jest.fn();   log('hello');   // The first argument of the first call to the function was 'hello'   expect(console.log).toHaveBeenCalledWith('hello'); }); 

If you're going with this approach don't forget to restore the original value of console.log.

Another option is to use jest.spyOn (instead of replacing the console.log it will create a proxy to it):

it('console.log the text "hello"', () => {   const logSpy = jest.spyOn(console, 'log');    console.log('hello');    expect(logSpy).toHaveBeenCalledWith('hello'); }); 

Read more here.

like image 123
JeB Avatar answered Sep 24 '22 02:09

JeB


Or you could do it like this:

it('calls console.log with "hello"', () => {   const consoleSpy = jest.spyOn(console, 'log');    console.log('hello');    expect(consoleSpy).toHaveBeenCalledWith('hello'); }); 
like image 23
Dozatron Avatar answered Sep 22 '22 02:09

Dozatron