通过运行似乎正在通过的mocha
来通过测试我遇到了麻烦。
测试:
describe('.get()',function() {
it('should be called once',function() {
// => Need to spy on this
var callback = function(err,data) {
console.log('I am called');
if (err) {
console.log('I am logging the error '+err);
} else {
console.log('I am logging the data '+data);
}
}
agentMock._response = {body:'something',headers:'headers'};
// => Start Spying
var spy = sinon.spy(callback);
sinon.spy(agentMock,'get');
baseRequest.get(spy); // refer (a) below
expect(agentMock.get).to.have.been.calledOnce;
expect(spy).to.have.been.calledOnce;
expect(spy).to.have.been.calledWith(null,'data');
});
});
我想测试callback
是否被调用。因此,我登录了回调的主体,而stdout也建议它被调用。
标准输出:
.get()
1) should be called once
I am called
I am logging the data something
0 passing (15ms)
1 failing
1) .get() should be called once:
AssertionError: expected spy to have been called exactly once, but it was called 0 times
详细信息:
(a)baseRequest.get
将数据作为bluebird
承诺返回。这可以通过将nodeback
传递给.get
本身或在.then
电话后链接.get
来使用。
BaseRequest.prototype.get = function(callback) {
// inner details
return invokeandPromisify(request,callback);
}
function invokeandPromisify(request, callback) {
return new Promise(function(resolve,reject) {
// Invoke the request
request.end(function(err,result) {
// Return the results as a promise
if (err || result.error) {
reject(err || result.error);
} else {
resolve(result);
}
});
}).nodeify(callback); // to have a node style callback
}
是否会因为我想间谍的回调传递给另一个函数(此处为invokeandPromisify
)并且间谍丢失?我只是在解释这个。
问候。
答案 0 :(得分:2)
由于baseRequest#get
返回一个promise,我会在promise被解决后进行断言。
见下面的例子:
it('should be called once',function(done) {
// => Need to spy on this
var callback = function(err,data) {
console.log('I am called');
if (err) {
console.log('I am logging the error '+err);
} else {
console.log('I am logging the data '+data);
}
}
agentMock._response = {body:'something',headers:'headers'};
// => Start Spying
var spy = sinon.spy(callback);
sinon.spy(agentMock,'get');
baseRequest.get(spy).finally(function() {
expect(agentMock.get).to.have.been.calledOnce;
expect(spy).to.have.been.calledOnce;
expect(spy).to.have.been.calledWith(null,'data');
done();
});
});
答案 1 :(得分:1)
通过添加done,您的测试应设置为async。然后在你的回调函数调用done()
请检查this