Skip to content

Instantly share code, notes, and snippets.

@campbellwmorgan
Last active December 29, 2016 09:59
Show Gist options
  • Save campbellwmorgan/e305cc36365fa2d052a7 to your computer and use it in GitHub Desktop.
Save campbellwmorgan/e305cc36365fa2d052a7 to your computer and use it in GitHub Desktop.
Model Mock for unit testing Sails.js applications
var Waterline, count, memory, _;
_ = require('lodash');
// sails-memory stores the adapter as a
// variable and it needs a different version for each instance
count = 0;
Waterline = require('waterline');
memory = require('sails-memory');
/**
* Creates an Instance of a Waterline model using the memory adapter
* @example
* MockModel = require('<this file>');
* MockModel({
* attributes:{
* name:'string'
* },
* tableName:'people'
* }, function(err, myMockModel){
* // ...do stuff with your model
* global.People = myMockModel
* });
* @param {object} This can just be the attributes, or the entire model file from your sails directory
* @param {function} callback once table has been synced - eg function(err, model){}
*/
module.exports = function(modelOptions, cb) {
var Model, config, connections, options, waterline;
count++;
options = _.merge({
connection: 'memory' + count,
tableName: 'testTable'
}, modelOptions);
Model = Waterline.Collection.extend(options);
waterline = new Waterline();
waterline.loadCollection(Model);
connections = {};
connections['memory' + count] = {
adapter: 'memory' + count
};
config = {
connections: connections,
adapters: {}
};
config.adapters['memory' + count] = memory;
return waterline.initialize(config, function(err, allItems) {
var TestTable;
if (err) {
return cb(err);
}
TestTable = allItems.collections[options.tableName.toLowerCase()];
return TestTable.sync(function(err) {
return cb(err, TestTable);
});
});
};
@bsushant-athena
Copy link

this method is not working for native methods.

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