Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test console.log output using Jest or other Javascript Testing Framework?

I have a function that runs asynchronously, console logging the numbers 1 through 5 in order after a random setTimeout. I want to write a test for this function using Jest. How do I write one that tests that the console.log is 1, 2, 3, 4, 5 ?

like image 777
fafafariba Avatar asked Jul 03 '17 17:07

fafafariba


People also ask

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.

What is Jest testing framework?

Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly.

Can Jest be used for functional testing?

- [Instructor] The Jest framework can be used to functionally test an application. The results can be included in a code coverage report, which is really useful. As a reminder, functional testing literally tests the functionality of an application.

Which command is used to run the 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.


1 Answers

Yes you can using jest.fn.

Here is an example:

File hello.js

console.log("Hello World");

File hello.test.js

let outputData = "";
storeLog = inputs => (outputData += inputs);
test("console log Hello World", () => {
  console["log"] = jest.fn(storeLog);
  require("./hello.js");
  expect(outputData).toBe("Hello World");
});
like image 167
Julien Landuré Avatar answered Sep 17 '22 11:09

Julien Landuré