-
-
Save devinivy/303c7a5c4865f96ed626 to your computer and use it in GitHub Desktop.
Sails.js: Stub Waterline query method with Sinon.js
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
var util = require('util'); | |
var _ = require('lodash'); | |
var sinon = require('sinon'); | |
/** | |
* Replaces a query method on the given model object with a stub. The query | |
* will still operate on a callback, and allow full access to waterline's | |
* deferred object. However, the query will not cause any I/O and instead | |
* will immediately resolve to the given result. | |
* | |
* If you pass an error object, the query will reject with the error. | |
* | |
* The original query method on the model object can be restored by calling | |
* model.method.restore() or stub.restore() | |
* | |
* @param {Object} model Waterline model object | |
* @param {string} method Query method name | |
* @param {*} result Object or Error | |
* @returns {Object} Sinon stub | |
*/ | |
module.exports = function(model, method, result) { | |
var originalMethod = model[method]; | |
return sinon.stub(model, method, function(criteria, cb) { | |
if(!_.isFunction(cb)) { | |
//pass-through to the deferred object | |
return originalMethod(criteria, cb); | |
} | |
if(util.isError(result)) { | |
return cb(result); | |
} | |
else if(_.isArray(result)) { | |
return cb(null, _.map(result, function(data) { | |
return new model._model(data); | |
})); | |
} | |
return cb(null, new model._model(result)); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OMG!! I just found the pendant of this for sails/waterline v1.x!