最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test console.log output with Jest? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 5

You 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);
发布评论

评论列表(0)

  1. 暂无评论