0

I am writing unit tests for my Node.js application using Mocha. Since my tests include a lot of redundant assert.equal(someFunction(arg1, arg2, arg3...), expected);, I thought of doing something like this:

var assertEqual = function(func, result)
{
  assert.equal(func, result);
}

descrirbe('someFunction()', function() {
    var arg1 = ...
    var arg2 = ...
    var func = someFunction;
    assertEqual(func, result)

    arg1 = ...
    arg2 = ...
    assertEqual(func, result);
}

This obviously does not work as func will bind its argument when declared. Is there a way to pass those arguments by reference in Javascript instead, so that I can keep modifying them and just call func instead of passing the arguments every time?

4

2 回答 2

2

只需让 assertEqual 返回一个函数,并让该函数成为您调用的函数而不是 func:

function assertEqual(func, expected) {
    return function() {
        var result = func.apply(this, arguments);//result if you called the old function normally
        assert.equal(result, expected);//pass/fail test
        return result; //return the result
    }
}

var func = assertEqual(oldfunc, result);
func(arg1, arg2);
func(arg3, arg4);

//example:
var func = assertEqual(function(a,b) {return a*5 - b}, 15);
func(4, 5); //=> 15, calls assert.equal(15, 15)
func(2, 8); //=> 5, calls assert.equal(5, 15)

*更新 * 使用范围变量进行与上述相同的测试
var arg1 = 4, arg2 = 5, result = 15; //一些随机范围变量 function somefunc() { return arg1*5 - arg2}; }

//same test and results as above
var func = assertEqual(somefunc, result);
func();
arg1 = 2;
arg2 = 8;
func();
于 2013-10-16T18:18:25.047 回答
0

在我看来,您可以将变量设为全局变量,而不是将它们作为参数传递给函数,您可以从代码中的任何位置设置/引用它们。

编辑:在您的示例中,参数实际上是全局的,只需将它们视为参数而不是参数。

于 2013-10-16T18:16:57.540 回答