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

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

+6
source share
1 answer

Yes you can use 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");
});
+6
source

All Articles