zoukankan      html  css  js  c++  java
  • 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)
    
  • 相关阅读:
    bzoj 3594: [Scoi2014]方伯伯的玉米田
    普通平衡树(指针splay)
    codeforces 475D. CGCDSSQ
    php 购物车功能
    PHP现阶段发现的不足点
    php 多维数据根据某个或多个字段排序
    redis可视化辅助工具
    Redis在window下安装以及配置
    hive数据操作
    hive 表分区操作
  • 原文地址:https://www.cnblogs.com/dajianshi/p/4128569.html
Copyright © 2011-2022 走看看