mocha框架下,異步測試代碼錯誤造成的問題----用例超時錯誤


  今天用抹茶(mocha)做個測試,發現有一個測試項目總是超時:

describe("DbFactory functions",function(){  
        it("query tables should return more than 0 rows",function(done){
            this.timeout(5000);            
            db.execQuery("show tables").then(function(data){   
          //錯誤就是這個地方,應該是data.data。 data.rows.length.should.greaterThan(
0); done(); },function(err){ done(err); }); }); });

上述代碼執行結果如下:只是超時引起的錯誤。

 4 passing (5s)
  1 failing

  1) DbFactory DbFactory functions query tables should return more than 0 rows:
     Error: timeout of 5000ms exceeded
      at null.<anonymous> (/var/node-v0.10.28-linux-x64/lib/node_modules/mocha/lib/runnable.js:158:19)
      at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

經過將timeout設為更長時間也沒有用,況且命令在mysql中是即時返回的,看來應該不是超時問題。

  由於測試對象DbFactory中使用了q的promise對象,開始懷疑是deferer對象一直沒有觸發,后經過調試發現deferer對象沒有問題,resolve也觸發了。

經故意引起錯誤,發現錯誤處理可以很快測試完畢,沒有問題!幾經周折,終於發現是should測試的對象的屬性搞錯了,應該是data而不是rows,改正過來后,測試很快通過。

  5 passing (184ms)

 

  看起來,mocha在異步模式下沒有抓住代碼的錯誤!不知道是不是算一個bug。后發現經過在測試代碼中加上try catch,可以抓到錯誤。

注:后來認真思考了下,確實不是mocha的問題,異步方法中的異常它沒有辦法抓取,也不能說是node的問題,這大概就是異步編程方式的痛吧。

describe("DbFactory functions",function(){  
        it("query tables should return more than 0 rows",function(done){
            this.timeout(5000);            
            db.execQuery("show tables").then(function(data){
                try{// 這里添加了捕獲代碼
                  data.rows.length.should.greaterThan(0);                    
                  done();
                }catch(err){done(err);}
            },function(err){
                done(err);
            });        
        });   
});

代碼修改后,可以抓到錯誤信息:

  4 passing (207ms)
  1 failing

  1) DbFactory DbFactory functions query tables should return more than 0 rows:
     TypeError: Cannot read property 'length' of undefined
      at /home/gzg/nodeDev/dzfu/test/dbFactory.test.js:22:26
      at _fulfilled (/home/gzg/nodeDev/dzfu/node_modules/q/q.js:794:54)
      at self.promiseDispatch.done (/home/gzg/nodeDev/dzfu/node_modules/q/q.js:823:30)
      at Promise.promise.promiseDispatch (/home/gzg/nodeDev/dzfu/node_modules/q/q.js:756:13)
      at /home/gzg/nodeDev/dzfu/node_modules/q/q.js:564:44
      at flush (/home/gzg/nodeDev/dzfu/node_modules/q/q.js:110:17)
      at process._tickCallback (node.js:419:13)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM