node.jspostgresqlunit-testingmocha.jsnodeunit

NodeJS unit testing of database routines using callbacks


Here is the problem: I have class WPSManager, which is exported as a module:

function WPSManager(dbclient) {
	var databaseclient = dbclient;

	this.getWrappers = function(excludeid, callback) {
		var query = "SELECT * FROM public.wps_methods WHERE id <> " + excludeid + " AND id > 88;";

		databaseclient.query(query, function(error, rows, fields) {
			callback(rows.rows);
		});
	} //end getWrappers()
} //end class

module.exports = WPSManager;

How can I test results of the query? I've tried variant with nodeunit (providing assertions in callback for getWrappers()), also the variant with mocha (example below). All of them are not making any assertions in the callback that I provide.

delete require.cache;
var assert     = require("assert");
var pg         = require("pg");
var WPSManager = require("./WPSManager");

/**
 * Database client initiation.
 */

var dbclient = new pg.Client("***");
dbclient.connect();
 
describe('WPSManager', function(){
  describe('getWrappers()', function(){
    it('should return list of wrappers', function(){
	  var wpsmanager = new WPSManager(dbclient);

	  wpsmanager.getWrappers(14, function(data) {
	    // This assertion is not performed
        assert.equal(5, data.length);
		done();
	  });	
    })
  })
});

So, here is the question - do any of unit testing tools for NodeJS can solve this question, or only thing that is available - using assert()? Assert is great, but it is not so fancy:)


Solution

  • Using jasmine-node (2.0.0) I would something like the below. I mocked your DB, but it should work with the real thing too.

    function WPSManager(dbclient) {
        var databaseclient = dbclient;
    
        this.getWrappers = function(excludeid, callback) {
            var query = "SELECT * FROM public.wps_methods WHERE id <> " + excludeid + " AND id > 88;";
    
            databaseclient.query(query, function(error, rows, fields) {
                callback(rows.rows);
            });
        } //end getWrappers()
    } //end class
    
    var dbclient = { 
        query : function ( query, callback ) {
            setTimeout( function () {
                callback( null, { rows:Array(5) }, null );
            }, 500);
        }
    };
    
    //var dbclient = mockDB;
    //var dbclient = new pg.Client("***");
    //dbclient.connect();
    
    describe('WPSManager', function(){
        describe('getWrappers()', function(){
            it('should return list of wrappers', function (done) {
    
                var wpsmanager  = new WPSManager(dbclient);
    
                wpsmanager.getWrappers(14, function(data) {
                    expect(data.length).toBe(5);
                    done();
                });
            });
        });
    });