我正面臨着通過運行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
是否被稱爲與否。因此,我登錄了回調的主體,標準輸出也表明它正在被調用。
標準輸出:
.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
詳情:
(一)baseRequest.get
返回數據爲bluebird
承諾。這可以通過在nodeback
到.get
本身或通過在.get
呼叫之後鏈接.then
來使用。
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
這裏)和間諜丟了?我只是在解釋這一點。
問候。
謝謝,救了我的一天!你能詳細說一下這裏有什麼問題,因爲我已經通過設置'agentMock._response'的值來設置響應了。 – darxtrix
之後不是同步測試嗎?我沒有得到它。 – darxtrix
承諾是異步的,所以你的測試也必須是異步的。我使用了'#finally'來確保當promise被解析時斷言,然後調用'done()'來表示異步測試的結束。 – JME