(This is similar to this question: How to set up separate test and development database in meteor, however it's 2 years old and meteor has changed a lot since then.)
I'm trying to create my own package and I want to run unit tests. I want to ensure that my queries are correct, so I want to actually run queries against a test database instead of just stubbing the functions.
I have two questions:
Ideally, I'd a setup step to clear than populate the test database, so I always know exactly what data is in each.
I'm a Tinytest novice (though I've used other unit test frameworks), so code samples are much appreciated.
Here's an example similar to what we use:
var resetCollection = function(name) {
var Collection = this[name];
if (Collection)
// if the collection is already defined, remove its documents
Collection.remove({});
else
// define a new unmanaged collection
this[name] = new Mongo.Collection(null);
};
reset = function() {
var collections = ['Comments', 'Posts'];
// reset all of the collections
_.each(collections(function(name) {resetCollection(name);}));
// insert some documents
var postId = Posts.insert({title: 'example post'});
Comments.insert({postId: postId, message: 'example comment'});
};
Tinytest.add('something', function(test) {
reset();
var post = Posts.findOne();
var comment = Comments.findOne();
return test.equal(comment.postId, post._id);
});
At the start of each test we call reset
which cleans up the database and creates the necessary collections.
How can I tell Meteor to run against a test database instead of my real one?
When you test your packages, a separate database will be created for you. There is no need to manually specify your db path.
What's the best way to easily populate that test database with data?
The example above should give you some pointers. I've found the best way to avoid conflicts between packages is to use unmanaged collections in tests (name = null
). The resetCollection
function should correctly avoid redefining any managed collections which are exported by other packages. Also see this question for more details.