我正在尝试使用supertest和nock在我的Express应用程序中测试中间件函数,但是我遇到的问题是,我设置的路由由早期的中间件检查,以确保传入的{{1}上存在会话属性对象。
我需要以某种方式在运行测试之前模拟会话对象,但我不确定如何处理它。首先让我分享一些代码:
router.js
req
routes.js
app.use('/api', helpers.hasAccessToken, require('./routes.js'));
helpers.js
router.route('/*')
.get(routesController.fetch)
routesController.js
module.exports.hasAccessToken = function(req, res, next) {
if(req.session.accessToken){
next();
} else {
res.status(401).send('LOGIN_SESSION_ENDED');
}
};
routesController.spec.js
module.exports.fetch = function(req, res) {
var options = helpers.buildAPIRequestOptions(req);
request(options, function(err, response, body){
res.status(response.statusCode).send(body);
});
};
我的测试失败,因为var app = require('./index.js'),
request = require('supertest')(app),
expect = require('chai').expect,
nock = require('nock');
describe('GET requests', function(){
beforeEach(function(){
nock('https://10.105.195.12:8243')
.get('/v1/schemes')
.reply(200, {foo:'bar'});
});
it('should return a 200 HTTP status code', function(done){
request
.get('/api/schemes')
.end(function(err, res){
expect(res.status).to.equal(200);
done();
});
});
});
的值是401.我正在使用快速会话,但我想知道我是否有某种方式可以获得我的测试套件中的res.status
对象并设置运行任何测试之前的accessToken属性的值。
有人可以提出任何意见或想法吗?
由于
答案 0 :(得分:2)
让我们为req.session
对象创建一些存根,其值在我们的控制之下。
var app = require('./index.js'),
request = require('supertest'), // no longer app here as we want to call parentApp
expect = require('chai').expect,
nock = require('nock');
describe('GET requests', function(){
var parentApp;
beforeEach(function(){
parentApp = express();
parentApp.use(function(req, res, next) { // lets stub session middleware
req.session = {};
next();
})
parentApp.get('/api', function(req, res, next) {
req.session.accessToken = true; // and provide some accessToken value
next();
})
parentApp.use(app);
nock('https://10.105.195.12:8243')
.get('/v1/schemes')
.reply(200, {foo:'bar'});
});
it('should return a 200 HTTP status code', function(done){
request(parentApp) // we are testing now app through parentApp and stubbed middleware
.get('/api/schemes')
.end(function(err, res){
expect(res.status).to.equal(200);
done();
});
});
});