我对node和它的测试生态系统还是个新手,所以如果我说得有点草率,请原谅。
我正在尝试存根一个被设置为原型属性的函数。在我的服务器代码中调用了这个函数Validate.prototype.isAllowed:
// Server
var router = require('express').Router();
var Validate = require('path/to/validator');
router.post('/jokes', function(req, res) {
var validate = new Validate();
if (!validate.isAllowed(req, 'jokes-create')) return res.end(403);
res.end(200);
});验证器代码如下所示:
// Validator
var validate = function() {};
validate.prototype.isAllowed = function(req, action) {
return true; // make things simple
};
module.exports = validate;我对之前启动的服务器运行API测试。下面是我的Mocha测试,其中我使用sinon来存根原型函数调用:
// Test
var Validate = require('path/to/validator');
var sinon = require('sinon');
var request = require('supertest-as-promised');
it('Fails with insufficient permissions', function(done) {
sinon.stub(Validate.prototype, 'isAllowed', function() {
return false;
});
request('www.example.com')
.post('/jokes')
.expect(403)
.then(function() {
Validate.prototype.isAllowed.restore();
done();
})
.catch(done);
});我观察到存根函数从未调用过,测试也从未通过过。问题出在哪里?
我还尝试向存根中添加两个参数,但这似乎没有帮助。看起来this question谈到了同样的问题,但对于常规的实例方法。此外,如果我将sinon.stub()位从测试移动到服务器,则所需的存根将生效。我有一种感觉,我的测试不会修补正在运行的服务器代码...
发布于 2016-01-19 07:36:23
我认为您应该在测试中创建一个新的验证器,然后为该验证器创建一个存根,而不是为原型创建一个存根。
试试这个:
it('Fails with insufficient permissions', function(done) {
var validate = new Validate();
sinon.stub(validate, 'isAllowed', function() {
return false;
});
request('www.example.com')
.post('/jokes')
.expect(403)
.then(function() {
validate.isAllowed.restore();
done();
})
.catch(done);
});此外,我不熟悉.restore()函数,但由于isAllowed是一个函数,因此我相信调用
validate.isAllowed.restore();不会起作用。(或者我错过了什么?)
发布于 2016-01-20 00:36:49
问题是服务器和测试处于不同的进程中。应从测试过程中启动服务器,以使存根正常工作。
这里有一个example self-contained Gist演示了这一想法。
https://stackoverflow.com/questions/34865596
复制相似问题