jeh*_*jeh 27 mocha.js node.js express sinon proxyquire
我在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;
Run Code Online (Sandbox Code Playgroud)
我想覆盖或模拟isAuthenticated返回此
auth.isAuthenticated = function(req, res, next) {
return next();
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
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);
});
Run Code Online (Sandbox Code Playgroud)
我尝试使用proxyquire模拟index.js - 我想我需要存根路由器?我也试过在测试中覆盖
app.use('/subscriptions', require('./api/subscription'));
Run Code Online (Sandbox Code Playgroud)
必须有一种简单的方法来模拟它,所以我不需要验证请求.有任何想法吗?
Ser*_*pin 25
您可以使用sinon存根isAuthenticated的方法,但你应该做一个参考之前auth.isAuthenticated被设置为一个中间件,所以你需要在之前index.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);
});
Run Code Online (Sandbox Code Playgroud)
请注意,即使在auth.isAuthenticated恢复之后,现有app实例也会将存根作为中间件,因此app如果由于某种原因需要获取原始行为,则需要创建另一个实例.
| 归档时间: |
|
| 查看次数: |
8725 次 |
| 最近记录: |