I need to test what console.log() printing. For example:
console.log("one %s three", two) ==> "one two three"
How can I get this final message ("one two three") using Jest?
P.s. It is important to check printing, not input parameters. Is it possible?
I need to test what console.log() printing. For example:
console.log("one %s three", two) ==> "one two three"
How can I get this final message ("one two three") using Jest?
P.s. It is important to check printing, not input parameters. Is it possible?
Share Improve this question edited Jun 23, 2022 at 18:55 Nikita Polevoy asked Jun 23, 2022 at 18:31 Nikita PolevoyNikita Polevoy 3697 silver badges20 bronze badges 4- instead of testing what console.log prints.; test the variable "two" – boop_the_snoot Commented Jun 23, 2022 at 18:33
- Why you want to test console.log, why not just test the value ? console.log is already well tested – Code Maniac Commented Jun 23, 2022 at 18:33
- @Code Maniac Someone could have console.log = function(str) {console.error("something else")} – IT goldman Commented Jun 23, 2022 at 18:36
- I need to test output of winston's wrapper. I believe it will be same principal as console.log testing. – Nikita Polevoy Commented Jun 23, 2022 at 18:38
1 Answer
Reset to default 5You may not want to test console.log
internal functionality (ensure that "one two three" gets printed) as that's not something you developed. The idea of unit tests is testing your own code and not external functionality, you just assume its gonna work as you would expect it to do. If it suddenly didn't do what you were expecting it's not like you are going to fix console.log
inner code/functionality.
However what you could validate is that console.log
gets called with the parameters you are expecting, which in this case you could achieve by spying on the log
method:
const logSpy = jest.spyOn(console, 'log');
// I assume two is a variable? If not then don't forget to double quote like "two"
expect(logSpy).toHaveBeenCalledWith("one % three", two);