Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Mongoose Node.JS app

I'm trying to write unit tests for parts of my Node app. I'm using Mongoose for my ORM.

I've searched a bunch for how to do testing with Mongoose and Node but not come with anything. The solutions/frameworks all seem to be full-stack or make no mention of mocking stuff.

Is there a way I can mock my Mongoose DB so I can return static data in my tests? I'd rather not have to set up a test DB and fill it with data for every unit test.

Has anyone else encountered this?

like image 475
benui Avatar asked Sep 25 '11 09:09

benui


1 Answers

I too went looking for answers, and ended up here. This is what I did:

I started off using mockery to mock out the module that my models were in. An then creating my own mock module with each model hanging off it as a property. These properties wrapped the real models (so that child properties exist for the code under test). And then I override the methods I want to manipulate for the test like save. This had the advantage of mockery being able to undo the mocking.

but...

I don't really care enough about undoing the mocking to write wrapper properties for every model. So now I just require my module and override the functions I want to manipulate. I will probably run tests in separate processes if it becomes an issue.

In the arrange part of my tests:

// mock out database saves
var db = require("../../schema");
db.Model1.prototype.save = function(callback) { 
    console.log("in the mock");
    callback();
};
db.Model2.prototype.save = function(callback) {
    console.log("in the mock");
    callback("mock staged an error for testing purposes");
};
like image 110
keza Avatar answered Sep 17 '22 12:09

keza