Mocha chai 请求超时 res.json

Mocha chai request time out exceed on res.json

我正在使用 chai 代理来测试登录,但我得到

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: 'test@test.com', _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/account/me”中,我有:

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

我的已认证:

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();

从不 returns 500。如果我将状态 (500) 更改为状态 (200),一切正常(当然不是测试)。

在 Describe 中添加,或在 it 之前添加。你应该使用 Async 库来链接这些调用。

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

代码中有 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 回调将永远不会被调用——最终导致 "Error: timeout of 2000ms exceeded."。相反,只有 return 代理调用结果就可以了:

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