I use jasmine-node to run tests against my nodejs functions. As a newbie to nodejs and mongodb, the first thing I came across was testing some database calls, and I was immediately stuck due to the asynchronous nature of nodejs.
What I want to do:
1) Add the add function to add new records to the mongodb table
2) Get the status bar from this function to check the status of the action
Below is the code for my specification. In the beforeEach call beforeEach I initialize the database. As you can see in the implementation, it is created only once because of the condition, if it already exists.
var mongo = require('../mongo.js'); describe('mongo', function() {
Now for each database query, I can define a callback function that runs when the query was successfully completed. What I donβt know how to achieve is the result of the result of the mongodb callback back to the specification.
This is the current implementation of the database functions:
var mongo = require('mongodb'), Server = mongo.Server, Db = mongo.Db; var server = new Server('localhost', 27017, {auto_reconnect: true}); var db = new Db('exampleDb', server); var collection = false; // initialize database var init = function() { if (collection === false) { db.open(dbOpenHandler); } }; var dbOpenHandler = function(err, db) { db.collection('myCollection', dbCollectionHandler); }; var dbCollectionHandler = function(err, coll) { collection = coll; }; /** returns the current db collection status * @return object db collection */ var getCollection = function() { return collection !== false; }; /** Add a new item to the database * @param object item to be added * @return string status code */ var add = function(item) { var result = collection.insert( item, {safe: true}, function(err) { // !! PROBLEM !! // this return call returns the string back to the callee // question: how would I return this as the add function return value return 'added'; }); }; // module export functions exports.init = init; exports.getCollection = getCollection; exports.add = add;
I am also open to other approaches on how to test database calls in mongodb. I read a bunch of articles on this topic, but none of them relate to my specific case.
Decision
Finally, and with the help of JohnnyHK's answer, I managed to get it to work with a callback. Take a look at the following test case to see what I did:
it('should create a new item', function() { var response; mongo.add(item, function( err, result) {