如何在Express中模拟中间件跳过unit testing的身份validation?
Express中有以下内容
//index.js var service = require('./subscription.service'); var auth = require('../auth/auth.service'); var router = express.Router(); router.post('/sync', auth.isAuthenticated, service.synchronise); module.exports = router;
我想覆盖或模拟isAuthenticated返回这个
auth.isAuthenticated = function(req, res, next) { return next(); }
这是我的unit testing:
it('it should return a 200 response', function(done) { //proxyquire here? request(app).post('/subscriptions/sync') .set('Authorization','Bearer '+ authToken) .send({receipt: newSubscriptionReceipt }) .expect(200,done); });
我试过使用proxyquire嘲笑index.js – 我想我需要存根路由器? 我也尝试在testing中覆盖
app.use('/subscriptions', require('./api/subscription'));
必须有一个简单的方法来嘲笑这个,所以我不需要validation请求。 有任何想法吗?
您可以使用sinon
来存储isAuthenticated
方法,但是您应该在将auth.isAuthenticated
的引用设置为中间件之前这样做,因此在您之前需要创buildindex.js
和app
。 最有可能你会想在beforeEach
钩:
var app; var auth; beforeEach(function() { auth = require('../wherever/auth/auth.service'); sinon.stub(auth, 'isAuthenticated') .callsFake(function(req, res, next) { return next(); }); // after you can create app: app = require('../../wherever/index'); }); afterEach(function() { // restore original method auth.isAuthenticated.restore(); }); it('it should return a 200 response', function(done) { request(app).post('/subscriptions/sync') .set('Authorization','Bearer '+ authToken) .send({receipt: newSubscriptionReceipt }) .expect(200,done); });
请注意,即使在auth.isAuthenticated
恢复之后,现有的app
实例也会作为中间件存在,所以如果您需要通过某种原因获取原始行为,则需要创build另一个app
实例。