Skip to content

Instantly share code, notes, and snippets.

@DanWilkerson
Last active January 12, 2018 16:23
Show Gist options
  • Save DanWilkerson/76c5a5dbca8a15cc6310bd98277e0260 to your computer and use it in GitHub Desktop.
Save DanWilkerson/76c5a5dbca8a15cc6310bd98277e0260 to your computer and use it in GitHub Desktop.
Testing Policies in Sails JS ^v0.12
/**
* Exposes policies during testing to allow for stubbing when testing controllers.
* Useful when you need to bypass a policy for authorized controllers.
*
* Originally created by @joepuzzo (https://github.com/joepuzzo)
* Updated by @notdanwilkerson (https://github.com/notdanwilkerson)
*
* Usage (in test file):
*
* let authStub;
*
* before(done => {
*
* authStub = sinon.stub(global.mocks.policies, 'googleauth');
* // Forces call of next()
* authStub.callsArg(2);
*
* done();
*
* });
*
* // ... test body
*
* after(done => {
*
* authStub.reset();
* done();
*
* });
*/
const Sails = require('sails');
global.mocks = {
policies: {}
};
before(function(done) {
this.timeout(15000);
Sails.lift({
moduleLoaderOverride: policyModuleLoaderOverride
}, done);
});
after(done => {
Sails.lower(done);
});
function policyModuleLoaderOverride(sails, origModuleLoader) {
const loadPoliciesOrig = origModuleLoader.loadPolicies;
return {
loadPolicies: cb => {
loadPoliciesOrig(addMocks(cb));
}
};
}
function addMocks(cb) {
return function addMocksCb(err, policies) {
if (err) return cb(err);
let id;
for (id in policies) {
let policy = policies[id];
let mockPolicy;
global.mocks.policies[id] = policy;
mockPolicy = Object.assign(makeMock(id), policy);
policies[id] = mockPolicy;
}
cb(null, policies);
};
}
function makeMock(id) {
return (req, res, next) => global.mocks.policies[id](req, res, next);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment