Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm just getting set up with Jest and I've successfully written unit tests that test the DOM. I have a library that types things on the screen, so I'm able to test just fine. In some cases, instead of throwing an error, my library will spit out a console.warn or console.log. Is it possible to use Jest to test that these console messages are happening?

like image 894
The Qodesmith Avatar asked Jun 03 '17 14:06

The Qodesmith


People also ask

How Jest tests use Jsdom?

Jest uses jsdom to provide an environment that behaves much like a browser's DOM or document. Each test file gets a single instance of jsdom, and changes aren't reset between tests inside the file. It's a best practice to clean up between tests so that a test's output doesn't affect any other test.

Does console log work in Jest?

Jest by default prints all console. log (warnings, errors, etc) messages to the console. That's great - it helps you understand what's going on in your code when tests run.

Does Jest use Jsdom?

Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment setting. If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run.

What is Jest environment Jsdom?

By default, jest uses the node testEnvironment. This essentially makes any tests meant for a browser environment invalid. jsdom is an implementation of a browser environment, which supports these types of UI tests.


2 Answers

You can set console.log to by a spy like this:

global.console = {
  warn: jest.fn(),
  log: jest.fn()
}

// run your code

expect(global.console.log).toHaveBeenCalledWith('test')

As your test file runs in a separate thread you don't need to reset console to the original methods

like image 145
Andreas Köberle Avatar answered Sep 18 '22 05:09

Andreas Köberle


Suppose you want test a function like this by printing a message:

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

You can use jest.spyOn function to change how console.log function behaves.

function sayHello () { console.log('Hello!') };
describe('logging "Hello"', () => {
  const log = jest.spyOn(global.console, 'log');
  sayHello();
  it('should print to console', () => {
    expect(log).toHaveBeenCalledWith('Hello!');
  });
});

OR you can redefine console object and add a key with jest.fn value, like this:

describe('sayHello prints "Hello!"', () => {
  const log = jest.fn()
  global.console = { log }
  sayHello()
  expect(log).toHaveBeenCalledWith('Hello!')
}
like image 35
Purkhalo Alex Avatar answered Sep 21 '22 05:09

Purkhalo Alex