17

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 ?

fafafariba
  • 335
  • 1
  • 2
  • 12

1 Answers1

25

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");
});
Julien Landuré
  • 266
  • 3
  • 2
  • 5
    you should store the original console.log function in a variable and after the test finished restore the original console.log, if not this might mess with other possible tests – ncubica Jan 07 '20 at 23:48
  • That answer shows how to check whether `console.log` is called, not the actual content in stdout, it is not the same, unfortunately. – Parzh from Ukraine Feb 04 '21 at 13:01