TDD with a fake for Mongoose

I’m working on a little personal side project using nodejs, backbone and mongo.  It’s actually a rewrite of something I wrote in .Net about a year ago. But I’m trying to expand it and also trying to practice TDD more.  About a year ago I made up my mind that I was done saying I was a proponent of testing, and decided to start living it. I do TDD at work, and it would be very hypocritical of me to not do it at home.

One area that I was getting hung up on was doing queries against mongoose schemas using TDD. Specifically, if I want to do a .find() operation. The first test I got away with a simple override of the find function in my tests:

User.findById = function(id, callback){
callback(new User({id: id});
}

And that fit my needs, it returned a user with whatever id I wanted. But it didn’t take long to get past the usefulness of that.

The case I was really wanting to test was a user has a bunch of activities that occur on specific dates. I wanted to test that passing in a date would filter my results by that date. It seemed pointless to write a function like the one above.

Every google search I did with the combination of mongoose, fake, tdd, stub didn’t really return what I wanted. Essentially, what everyone does to TDD with mongoose is they set up a local copy of mongo and hit it. That’s fine, I suppose. I don’t like hitting any DBs in my unit tests, and I didn’t like the idea of ensuring the state of the DB before each test.  I was at a stand-still for a while.

Then I found a great little library called underscore-query. It allows you to query underscore collections using the same mongoose style selectors.  Why was this so great? Because now I could create a fake database in my test. And “fake database” is just a fancy way to say “I created an array.”

[gist id=”38ccb31aafbbb4bae813″]

That’s it, using _.query will query my collection with the same syntax that I query my mongoose collection.

Now I don’t have to make sure I do a setup nor tear down in between each test. Instead I can focus on the functionality of my code. For example, making sure it only compares by date, and ignores the time component.

If you want to do pure TDD against a mongoose ODM, I suggest checking out underscore-query.


Leave a Reply

Your email address will not be published. Required fields are marked *