Sinon.js在一个对象内部存储一个匿名函数

所以我正在testing我的代码,我面临一个testing在unit testing函数内部被调用的匿名函数的问题。 为什么我没有让匿名函数成为一个名为function的实例,是因为我需要closures一些匿名函数中使用的unit testing函数的variables。 举例说明:

function funcBeingTested(done, arg1) { var self = this; ... self.array.push({ "arguments": [ "x", "y", function (error, result) { // do some stuff with arg1... done(error, arg1); }, "z" ] }); ... self.run(); // Eventually will call the anonymous function above from 'self.array' } 

现在,我的问题是有没有一种方法来testing使用sinon.js匿名函数内部发生了什么?
有人可以用特定的参数作为funcBeingTested()的unit testing的一部分来调用它?

编辑:为了清除任何我想要实现的误解,我希望能够unit testing匿名函数它自己,并涵盖所有可能的分支机构,以获得100%的覆盖率。 我已经知道如何检查done()callback是否被调用,以及使用sinon.js的参数,问题是我将如何在隔离中testing匿名函数,并用特定的参数调用它以涵盖所有可能的分支。

您可以通过定义done函数并对其进行监视来testing匿名函数。 您需要知道在调用匿名函数时是否使用正确的参数调用此函数。

例如:

 // Define the `done` function. var doneFunction = function (error, args) { // do something }; // Spy on the `done` function to register calls. var doneSpy = sinon.spy(doneFunction); // Test the funcBeingTested funcBeingTested(doneFunction, someArg); // Check that doneFunction was called assert(doneSpy.calledWith(someArg)); 

您可以阅读更多关于Sinon的Spy API