如何使用 Jest 或其他 Javascript 测试框架测试 console.log 输出? [英] How to test console.log output using Jest or other Javascript Testing Framework?
本文介绍了如何使用 Jest 或其他 Javascript 测试框架测试 console.log 输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个异步运行的函数,控制台在随机 setTimeout 之后按顺序记录数字 1 到 5.我想使用 Jest 为这个函数编写一个测试.我如何编写一个测试 console.log 是 1, 2, 3, 4, 5 的程序?
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 ?
推荐答案
是的,您可以使用 jest.fn
.
这是一个例子:
文件 hello.js
console.log("Hello World");
文件 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");
});
这篇关于如何使用 Jest 或其他 Javascript 测试框架测试 console.log 输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文