坚持摩卡和超级应用程序会议

我有一个快速的应用程序,authentication由JWT处理,我只需login后在会话中存储令牌。

req.session.JWToken = '<token>'; 

身份validation中间件如下所示:

 this.use('(^\/admin')', expressJWT({ secret: 'secret', getToken: function fromHeaderOrQuerystring (req) { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { return req.headers.authorization.split(' ')[1]; } else if (req.query && req.query.token) { return req.query.token; } else if (req.session.JWToken) { return req.session.JWToken; } return null; } }).unless({path: ['/login', '/signup']})); 

我需要testing这个使用摩卡和supertest,我试了下面的代码:

 var app = require('./../app'); var request = require('supertest'); describe('app', function() { var agent = request.agent(app); it('should signin', function(done) { agent .post('/login') .send({_email: '<email>', _password: '<password>'}) .expect(200, done) .end(function(err, res){ if(err) throw err; done(); }); }); // how to persist session here ? it('should get a restricted page', function(done) { agent .get('/admin') .expect(200) .end(function(err, res){ if(err) throw err; done(); }); }); }); 

不知道如何坚持第二次会议。请引导我一个方向。

我昨天遇到了同样的问题,并找出答案。 尝试在describe块之外设置agent

 var app = require('./../app'); var request = require('supertest'); var agent = request.agent(app); describe('app', function() { it('should signin', function(done) { agent .post('/login') .send({_email: '<email>', _password: '<password>'}) .expect(200, done) .end(function(err, res){ if(err) throw err; done(); }); }); // how to persist session here ? it('should get a restricted page', function(done) { agent .get('/admin') .expect(200) .end(function(err, res){ if(err) throw err; done(); }); }); }); 

如果这不起作用,请尝试使用sinon在beforeEach循环中执行loginPOST。

 beforeEach((done) => { agent .post('/login') .send({_email: '<email>', _password: '<password>'}) .end((err, res) => { if (err) throw err; done(); }); }); 

如果这不起作用,请确保您的emailpassword参数是正确的。

Interesting Posts