Skip to content

Instantly share code, notes, and snippets.

@devinivy
Forked from wxactly/stubQueryMethod.js
Last active September 29, 2020 10:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devinivy/303c7a5c4865f96ed626 to your computer and use it in GitHub Desktop.
Save devinivy/303c7a5c4865f96ed626 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));
});
};
@Nielio
Copy link

Nielio commented Sep 29, 2020

OMG!! I just found the pendant of this for sails/waterline v1.x!

model._transformer.unserialize(record);

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