Skip to content

Instantly share code, notes, and snippets.

@wxactly
Last active August 29, 2015 14:06
Show Gist options
  • Save wxactly/f2258078d802923a1a0d to your computer and use it in GitHub Desktop.
Save wxactly/f2258078d802923a1a0d to your computer and use it in GitHub Desktop.
Sails.js: Stub Waterline query method with Sinon.js
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));
});
};
@wxactly
Copy link
Author

wxactly commented Sep 14, 2014

I'm currently only using this to test find*() methods - YMMV if you need to stub update(), delete(), etc...

@devinivy
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment