2016-09-26 77 views
0

我用柴剂来测试洛,但我越来越摩卡柴请求超时超过上res.json

Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test 

it('POST /api/v1/account/me status 500', function(done) { 
    var agent = chai.request.agent(server); 
    agent.post('/api/v1/account/login') 
     .send({_email: '[email protected]', _password: 'testtest'}) 
     .then(function(res){ 
     agent.get('/api/v1/account/logout') 
      .then(function(res2){ 
       agent.get('/api/v1/account/me') 
        .then(function(res3){ 
         res2.should.have.status(500); 
         done(); 
        }); 
     }); 
    }); 
}); 

在我“/ API/V1 /帐号/我”,我有:

router.get('/me', auth.isAuthenticated, function(req, res){ 
    res.json(new Response({error:false, results: req.session.user})) 
}); 

而且我isAuthenticated:

isAuthenticated: function (req, res, next) { 

    var sess = req.session; 
    if(sess.user) 
     return next(); 

    res.status(500).json(new Response({error:true})).end(); 
    return; 
} 

的问题是,

res.status(500).json(new Response({error:true})).end(); 

永远不会返回500.如果我改变状态(500)与状态(200),一切工作正常(当然不是测试)。

回答

0

代码有2个问题。

  1. .then接受两个回调参数:第一个处理成功响应(200 OK),第二个处理失败响应(404,500等)。因此,您需要将断言代码放在第二个回调中。示例代码:

    agent.get('/api/v1/account/me') 
        .then(function(res3) { 
         // assertion statements when response is successful. 
        }, function(res4) { 
         // assertion statements when response is failed. 
         res4.should.have.status(500); 
        }); 
    
  2. 不要使用done。当chai断言陈述失败时(res4.should.have.status(500)),它将抛出一个AssertionError,这意味着done回调将永远不会被调用 - 最终会导致“错误:超过2000ms的超时。”。相反,invokation导致刚刚return代理,它是好去:

    var agent = chai.request.agent(server); 
    return agent.post('/api/v1/account/login') 
          ... 
    
+0

它像一个魅力工作!非常感谢! – JVilla

0

加入描述内部,或之前。你应该使用异步库链接这些调用。

describe('',function(){ 
    this.timeout(15000); 
    it('', function(done){ 
     Async.series([], function(cb){ 
      function(cb){ 
       cb(); 
      }, 
      function(cb){ 
       cb(); 
      } 
     }, function(err){ 
      done(); 
     }); 
    }; 
}); 
+0

感谢回答。我不认为这是问题。另外,我想补充一点.then()在发送响应时执行。所以它在异步函数中工作正常。 – JVilla