2015-06-07 53 views
2

我正面臨着通過運行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這裏)和間諜丟了?我只是在解釋這一點。

問候。

回答

2

由於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(); 
    }); 

}); 
+0

謝謝,救了我的一天!你能詳細說一下這裏有什麼問題,因爲我已經通過設置'agentMock._response'的值來設置響應了。 – darxtrix

+0

之後不是同步測試嗎?我沒有得到它。 – darxtrix

+1

承諾是異步的,所以你的測試也必須是異步的。我使用了'#finally'來確保當promise被解析時斷言,然後調用'done()'來表示異步測試的結束。 – JME

1

通過添加完成,您的測試應該設置爲異步。然後在回調funtion調用來完成()

請檢查http://mochajs.org/#asynchronous-code

+0

'agentMock._response = {體: '某物',標頭: '報頭'};'立即設置響應。那麼,現在是異步嗎? – darxtrix

+0

好的,我應該叫它'done'。 – darxtrix