Last active
January 12, 2018 16:23
-
-
Save DanWilkerson/76c5a5dbca8a15cc6310bd98277e0260 to your computer and use it in GitHub Desktop.
Testing Policies in Sails JS ^v0.12
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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