我的API使用express-session
并根据req.session.user
对象的存在对任何请求进行身份验证,如下所示:
app.use(function(req, res, next) {
if (req.session.user) {
console.log('Authenticated request\n');
next();
} else {
console.log('Request not authenticated, request rejected\n');
res.status(403).json({'message': 'Request rejected'});;
}
});
我正在使用chai-http
为我的API编写测试,如下所示:
describe('test', function(){
it('/test', function(done){
chai.request(server)
.get('/test')
.end(function(err, res){
res.body.should.be.a('object');
});
});
});
问题
我希望请求通过上面的身份验证。如何将.session.user
对象添加到chai-http
个请求中?我应该使用supertest
吗?
答案 0 :(得分:0)
您是否使用护照进行身份验证,如果是这样,请参阅下文。如果不是:查看Passport-stub的这个实现,看看它如何劫持中间件来伪造用户:
https://github.com/gtramontina/passport-stub/blob/master/src/passport-stub.coffee
使用此技术,您可以将中间件插入应用程序以伪造用户
如果您使用护照:
如何使用passport-stub
我查看了https://github.com/gtramontina/passport-stub
这是我对受保护的/users
路线的测试:
//During the test the env variable is set to test
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHttp = require('chai-http');
var expect = chai.expect
var passportStub = require('passport-stub');
var User = require.main.require('models/User');
// https://gist.github.com/branneman/8048520#7-the-wrapper
var app = require.main.require('app');
chai.use(chaiHttp);
passportStub.install(app);
describe('Users Controller', (done) => {
var user, nock, github, mockToken, githubHost;
beforeEach((done) => { //Before each test we reset the database
User.query().del().then(() => {
var params = {name: 'bonzo', authtype: 'github', authid: '12345678'}
// Create a user so the db isn't empty
// May help us uncover odd bugs
new User(params).save()
.then((bonzo) => {
user = bonzo;
done();
})
})
});
describe('index', () => {
describe('without user', () => {
it('it should redirect to github.com home page', (done) => {
chai.request(app)
.get('/users')
.redirects(0)
.end((err, res) => {
expect(res.headers['location']).to.match(/^\//);
done();
});
});
});
describe('with user', () => {
it('it should display users list', (done) => {
passportStub.login({
get: function(){ return 'bonzo'; }
});
chai.request(app)
.get('/users')
.redirects(0)
.end((err, res) => {
expect(res.text).to.match(/bonzo/);
done();
});
});
});
});
});