我正在为我的应用程序设置测试,我希望使用 Sinon 检查一个方法被调用了 x 次,我的测试框架是 Mocha。
我怎样才能做到这一点,下面是我想测试的代码,我希望确保 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();
});
}
};
已尝试测试但无济于事,因为 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 似乎是一个异步请求,没有回调/ promise 。 这意味着您的测试会立即得到评估,而不是等待结果。 我建议使用回调或 promise 重写函数,以便您能够在处理完成的事件上采取行动,然后这应该可以工作:
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();
});
});
});
});
跳过 before 语句,因为这可能会干扰范围,可以在测试中调用同步的 sinon.spy。
另请注意,我在此声明中引入了一个回调:
it('应该调用 recursiveRequest() 10 次', function (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();
}
};
另请注意,您可以使用回调来处理错误。
关于javascript - Mocha 和诗乃的方法 spy ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28265054/