I'm fairly new to node
and its testing ecosystem, so please forgive me if this is a bit sloppy.
I'm trying to stub a function that is set as a prototype property. This function, Validate.prototype.isAllowed
, is being called inside my server code:
// 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);
});
The validator code looks like this:
// Validator
var validate = function() {};
validate.prototype.isAllowed = function(req, action) {
return true; // make things simple
};
module.exports = validate;
I run API tests against the server that was previously started. Here's my Mocha test where I use sinon to stub the prototype function call:
// 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);
});
I observe that the stub function is never called and the test never passes. Where's the gotcha?
I've also tried to add two parameters to the stub, but that didn't seem to help. Looks like this question talks about the same problem, but for regular instance methods. Also, if I move sinon.stub()
bit from the test to the server, the desired stub takes effect. I have a feeling that my test just won't patch the running server code...