Javascript Mocha测试蓝鸟驱动的节点式回调
通过运行Javascript Mocha测试蓝鸟驱动的节点式回调,javascript,node.js,mocha.js,sinon,bluebird,Javascript,Node.js,Mocha.js,Sinon,Bluebird,通过运行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
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');
});
});
我想测试是否调用了回调
。因此,我登录了回调的主体,并且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
承诺返回。这可以通过将节点回退
传递到.get
本身或通过链接。然后在.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
),而监视丢失了?我只是解释一下
注意。您的测试应通过添加“完成”设置为异步。然后在回调函数中调用done() 请检查因为
baseRequest#get
返回一个承诺,我会在承诺解决后做出断言
见下例:
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();
});
});
agentMock.\u response={body:'something',headers:'headers'}代码>立即设置响应。那么,它现在是异步的吗?谢谢,救了我一天!由于我已经通过设置agentMock的值来设置响应,您能详细说明一下这里的问题是什么吗?\u response
。这之后不是同步测试吗?我不明白。承诺是异步的,所以你的测试也必须是异步的。我使用了#finally
来确保在承诺得到解决时做出断言,然后调用done()
来发出异步测试结束的信号。是的,终于得到了。