我经常手动测试JavaScript函数的输出(通过简单地查看控制台中每个函数的输出),这通常非常繁琐。在JavaScript中,有没有办法自动测试一系列函数调用的输出,并返回所有未产生预期结果的测试?
checkOutput([["add(1, 2)", 3], ["add(2, 2)", 4]]); //if the input does not match the output in one of these arrays, then return the function call(s) that didn't produce the correct output
function checkOutput(functionArray){
//this function is not yet implemented, and should return a list of function calls that did not produce correct output (if there are any).
}
function add(num1, num2){
return num1 + num2;
}
答案 0 :(得分:2)
绝对。使用单元测试套件,例如QUnit。
我特别喜欢那个,它自夸它被各种jQuery项目使用。这是非常可靠的认可。
典型的测试看起来像这样......
test( "add test", function(num1, num2) {
ok( num1 + num2 == 42, "Passed!" );
});
而且,如果您不喜欢这个建议,请查看其他单元测试框架,请访问维基百科:JavaScript Unit Testing Frameworks。
答案 1 :(得分:2)
似乎像循环一样简单,eval
每个数组的第一个元素,并将其与第二个元素进行比较。
function checkOutput(functionArray) {
var check = function(e) {
return eval(e[0]) !== e[1];
};
if( Array.prototype.filter)
return functionArray.filter(check);
// shim in older browsers
var l = functionArray.length, i, out = [];
for( i=0; i<l; i++)
if( check(functionArray[i]))
out.push(functionArray[i]);
return out;
}
答案 2 :(得分:1)
也许你想切换到jasmine来测试javascript。
答案 3 :(得分:1)
我的测试库suite.js做了类似的事情。基本上语法如下所示:
suite(add, [
[[1, 2]], 3
]);
通常我使用部分应用程序绑定参数,所以我的测试看起来像这样:
suite(partial(add, 1), [
-5, 4,
2, 3
]);
并且达到了最终水平,我完全跳过了这些测试并定义了一个基于我生成测试的合同。为此我使用annotate.js。在这种情况下,我最终会得到以下内容:
// implementation
function adder(a, b) {
return a + b;
}
var add = annotate('add', 'adds things').on(is.number, is.number, adder);
// test some invariants now
suite(add, function(op, a, b) {
return op(a, b) == op(b, a);
});
我知道这不再是一个微不足道的代码了。这允许您为函数参数定义不变量,并且基于该信息,我们可以生成测试,文档等。
suite.js目前仅适用于Node环境,但如果有足够的兴趣,我不介意将其移植到浏览器,以便您可以在那里运行测试。
答案 4 :(得分:0)
查看QUnit。您基本上可以同时对所有功能进行测试。