2015-09-18 25 views
0

我對摩卡感到沮喪的一件事是,當測試失敗時,它們不會給出失敗線的實際錯誤消息,而是僅以結束錯誤:超時超過2000毫秒。確保在此測試中正在調用done()回調。使摩卡測試顯示實際的錯誤

取本試驗中,例如:

describe("myTest", function() { 
    it("should return valid JSON.", function(done) { 
     api.myCall("valid value").then(function(result) { 
      console.log(result); 
      var resultObj = JSON.parse(result); 
      assert.isFalse(resultObj.hasOwnProperty("error"), "result has an error"); 
      done(); 
     }); 
    }); 
}); 

的輸出是:

myTest 
{"error":null,"status":403} 
    1) should return valid JSON. 


    0 passing (2s) 
    1 failing 

    1) myTest should return valid JSON.: 
    Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test. 

的assert.isFalse失敗,但應該被顯示的消息( 「結果有錯誤」 )不顯示。事實上,處理似乎停在那裏,因爲done()永遠不會被調用。將該行取出並且測試通過,因爲調用了done()。

那麼,我錯過了什麼?爲什麼摩卡測試的行爲如此?我使用的實際測試庫:

var assert = require("chai").assert; 

有誰知道我做錯了,或者爲什麼這種行爲這種方式?

回答

1

它看起來像你的API使用承諾。在嘗試其他任何事情之前,我會建議檢查一下API的文檔中關於承諾的內容以及如何處理未處理的異常,因爲這可能是這裏發生的事情。某些承諾實施要求您在呼叫鏈末尾呼叫.done(),以確保未捕獲的異常將被處理。有些要求適當配置一些全球承諾設置。藍鳥文檔給出了一個很好的問題discussion

摩卡能夠在運行中的磨碼處理捕獲的異常:

var chai = require("chai"); 
var assert = chai.assert; 
chai.config.includeStack = true; 

describe("foo", function() { 
    it("let the exception be caught by Mocha", function(done) { 
     setTimeout(function() { 
      assert.isFalse(true, "foo"); 
      done(); 
     }, 1000); 
    }); 
}); 

這將導致輸出:

foo 
    1) let the exception be caught by Mocha 


    0 passing (1s) 
    1 failing 

    1) foo let the exception be caught by Mocha: 
    Uncaught AssertionError: foo: expected true to be false 
     at Assertion.<anonymous> (/tmp/t7/node_modules/chai/lib/chai/core/assertions.js:286:10) 
     at Assertion.Object.defineProperty.get (/tmp/t7/node_modules/chai/lib/chai/utils/addProperty.js:35:29) 
     at Function.assert.isFalse (/tmp/t7/node_modules/chai/lib/chai/interface/assert.js:297:31) 
     at null._onTimeout (/tmp/t7/test.js:8:20) 
     at Timer.listOnTimeout (timers.js:119:15) 
1

我遇到了同樣的在我代碼,使用Q作爲承諾。

當時的情況是:

  • then塊內的斷言失敗。
  • then塊的其餘部分(包括done()語句)未執行。
  • Q去尋找一塊catch塊,它不在那裏。
  • 這導致了一個'掛起'的承諾,從而導致摩卡2000毫秒超時。

我工作圍繞它做這樣的事情:

describe("myTest", function() { 
    it("should return valid JSON.", function(done) { 
     api.myCall("valid value").then(function(result) { 
      console.log(result); 
      var resultObj = JSON.parse(result); 
      assert.isFalse(resultObj.hasOwnProperty("error"), "result has an error"); 
      done(); 
     }) 
     .catch(function(err) { 
      console.error(err); 
      done(err); 
     }); 
    }); 
});