2016-09-23 136 views
1

當使用兩個嵌套的chai請求時,會話丟失。Mocha chai請求和快速會話

chai.request(server) 
    .post('/api/v1/account/login') 
    .send({_email: '[email protected]', _password: 'testtest'}) 
    .end(function(err, res){ 
     chai.request(server) 
     .get('/api/v1/user/me') 
     .end(function(err2, res2){ 
      //here i should get the session, but its empty 
      res2.should.have.status(200); 
      done(); 
     }); 
    }); 

而且我敢肯定,它在我的摩卡測試一個錯誤,因爲我想它(登錄,然後檢索會話)的測試外,會話被設置好的。

+0

你使用哪種方法來獲取會話?你可以在會話比較中加入'should'語句嗎? – shaochuancs

+0

感謝您的回覆。我沒有關於會話比較的應聲明。相反,我的「/ api/v1/user /」路由上有一箇中間件:isAuthenticated:function(req,res,next){ \t var sess = req.session; \t \t if(!sess.user) \t return next(); \t res.status(500).send({error:true}) \t}。所以如果沒有會話,我預計這將返回一個狀態500.如果會話設置我期望狀態200.但我總是得到500. – JVilla

回答

2

表示本身沒有任何本機會話支持。我猜你正在使用一些會話中間件,如https://github.com/expressjs/session

同時,我猜你正在使用chai-http插件發送HTTP請求。在chai-http中,爲了在不同的HTTP請求之間保留cookie(以便req.session在快速方面可用),您需要使用chai.request.agent而不是chai

這裏是你的代碼一個簡單的例子:

var agent = chai.request.agent(app); 
agent.post('/api/v1/account/login') 
    .send({_email: '[email protected]', _password: 'testtest'}) 
    .then(function(res){ 
      agent.get('/api/v1/user/me') 
        .then(function(res2){ 
         // should get status 200, which indicates req.session existence. 
         res2.should.have.status(200); 
         done(); 
    }); 
}); 

對於chai.request.agent,你可以參考http://chaijs.com/plugins/chai-http/#retaining-cookies-with-each-request

+0

謝謝!它像一個魅力工作! – JVilla