摩卡测试路线,req.session.code不确定



我想测试两个路由器,首先生成验证代码,然后在req.session.code中保留第二个检查代码。路由器:

`router.post('/code', (req, res) = > {
   let text = generateCode();
   req.session.code = text;
   res.json({message: text}); 
 })`
`router.post('/check_code' , (req, res) => {
   let c = req.body.code;
   console.log(c, req.session.code) //when test, req.session.code is undefined
   if (c.toUpperCase() !== req.session.code.toUpperCase()) {
      return res.json('error');
   }
   return res.json('ok');
})`

然后,我使用supertestmocha测试。

`describe('test', function() {
   let code; //check code as body
   it('get verification code', function(done) {
     request.agent(app)
        .post('/code')
        .expect(200)
        .end(function(err, res){
         if (err) return done(err);
         code = res.body.message;
          done();
      })
   })
   it('check verification code', function(done) {
     request.agent(app)
        .post('/check_code')
        .send({code: code}) 
        .expect(200)
        .end(function(err, res){
         if (err) return done(err);
         code = res.body.message;
          done();
      })
   })
})`

第一次传球,第二次失败,我用Postman手动测试,它有效,我打印了req.session:

`session {
  cookie:
   {path: '/',
    _expires:null,
    originalMaxAge: null,
    httpOnly: true
   },
   code: xxxx  //there is code when use postMan,but not in mocha
}`

我hava在我的代码中使用了.avent。那么,当某些值保持在会话中时,该如何测试路由器?我还没有找到同样的问题。

您正在为每个测试创建一个新的代理,但是如果您希望代理可以正确支持Cookies,则需要在测试中使用一个代理(因为代理商商店内部收到的cookie,随后使用同一代理商提出的请求将使用这些cookie(:

describe('test', function() {
   let agent = request.agent(app);
   let code; //check code as body
   it('get verification code', function(done) {
     agent.post('/code')...
   });
   it('check verification code', function(done) {
     agent.post('/code')...
   });
});

最新更新