Last active
December 29, 2016 09:59
-
-
Save campbellwmorgan/e305cc36365fa2d052a7 to your computer and use it in GitHub Desktop.
Model Mock for unit testing Sails.js applications
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 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); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this method is not working for native methods.