摩卡和锡诺方法间谍

我正在为我的应用程序设置testing,并且我希望检查使用Sinon的x次方法,我的testing框架是Mocha。

我怎么能做到这一点,下面是我想testing的代码,我期待确保recursiveRequest被createClients调用x次。

Nodezilla.prototype.createClients = function(batched, i){ var self = this; if(batched) batchRequests(); if(batched == false && i < this.virtualUsers){ // set timeout to help prevent out of memory errors setTimeout( function() { self.createClients(false, i+1); }, 0 ); }else{ this.recursiveRequest(); } }; Nodezilla.prototype.recursiveRequest = function(){ var self = this; self.hrtime = process.hrtime(); if(!this.halt){ self.reqMade++; this.http.get(this.options, function(resp){ resp.on('data', function(){}) .on("end", function(){ self.onSuccess(); }); }).on("error", function(e){ self.onError(); }); } }; 

尝试testing,但无效callCount返回0。

 var assert = require('assert'), sinon = require('sinon'), nz = require('../Nodezilla'), nt = new nz("localhost", 10); describe('Nodezilla', function(){ describe('createClients', function(){ before(function() { sinon.spy(nt, "recursiveRequest"); }); it('should call recursiveRequest() 10 times', function(){ nt.createClients(false, 0); assert(nt.recursiveRequest.callCount); }); }); }); 

createClients似乎是一个asynchronous请求,没有callback/承诺。 这意味着您的testing立即进行评估,不会等待结果。 我build议重写一个callback或承诺的function,以便您可以采取行动处理完成,然后这应该工作:

 var assert = require('assert'), sinon = require('sinon'), nz = require('../Nodezilla'), nt = new nz("localhost", 1); describe('Nodezilla', function () { describe('createClients', function () { it('should call recursiveRequest() 10 times', function (itCallback) { // Moved into the test: sinon.spy(nt, "recursiveRequest"); nt.createClients(false, 0, function(){ // Needs to wait for action to actually be called: assert(nt.recursiveRequest.callCount == 10); // Now that the test is actually finished, end it: itCallback(); }); }); }); }); 

跳过前面的语句,因为这可能会干扰范围,sinon.spy是同步的可以在testing中调用。

还要注意我在这个语句中引入了一个callback: it('should call recursiveRequest() 10 times', function (callback) {在内部callback被调用之前保持testing结束。

编辑:至于添加callback,我不知道什么是batchRequests()做,但像这样:

 Nodezilla.prototype.createClients = function (batched, i, cb) { var self = this; if (batched) batchRequests(); if (batched == false && i < this.virtualUsers) { // set timeout to help prevent out of memory errors setTimeout(function () { self.createClients(false, i + 1, cb); }, 0); } else { this.recursiveRequest(cb); } }; 

接着:

 Nodezilla.prototype.recursiveRequest = function (cb) { var self = this; self.hrtime = process.hrtime(); if (!this.halt) { self.reqMade++; this.http.get(this.options, function (resp) { resp.on('data', function () { }) .on("end", function () { self.onSuccess(); cb(); }); }).on("error", function (e) { self.onError(); cb(); }); } else { // I assume you are doing nothing in this case, so just call the callback: cb(); } }; 

另外请注意,您可以使用callback进行error handling。