EzDevInfo.com

nodeunit

Easy unit testing in node.js and the browser, based on the assert module.

Nodeunit command not found?

I'm running on Windows 7 and have node installed fine with cygwin. I am following along on the how to on mcmahon's website for nodeunit: http://caolanmcmahon.com/posts/unit_testing_in_node_js .

I used npm to install nodeunit and it said it had installed fine but when I go to invoke it, nodeunit, it says command not found in all the different directories.

Do I have to set some kind of path variable maybe?


Source: (StackOverflow)

Nodeunit - JSCovrage


Is there a way to use JSCoverage to have code coverage for nodeunit?

I know there is nodeunit2, but my code is not in lib, and I do not want to restructure my project.


Source: (StackOverflow)

Advertisements

tearDown() that is only executed after ALL tests have run?

I'm trying to write some integration tests in NodeUnit. My tests work fine, but the test runner hangs because knex is keeping a PostgreSQL DB connection open.

I can get it to release by calling knex.destroy() in my tearDown, but unfortunately then the DB is no longer available for the rest of my test suite (and tests in other files as well).

Is there a way to implement a tearDown that runs only once, after ALL tests have run?


Source: (StackOverflow)

Nodeunit sample with websockets

I am trying to apply the TDD principles to an application using node.js and nodeunit for the unit test. I am struggling trying to create a test case that is able to use websockets to test the application communication protocol.

I am quite new to TDD, so, is this approach correct for the TDD ?

Do you know where can I find samples to to this ?

EDIT: I have a working sample. However I have the problem that the server takes 15 seconds in closing it self. I appreciate feedback about this code (this is WIP).

file tests/websocket.js

var Server = require('../tests/server.js').Server;
var wsServer = new Server();

var ioclient = require("socket.io-client");

var testCase = require('nodeunit').testCase;

exports.server = testCase({

    setUp: function(callback) {

        wsServer.initialize();

        wsServer.addEvent('connection',function(socket){
            socket.on('ping',function(data){
                socket.emit('ping', { value: 'ok' });
                socket.disconnect();
            });
        });

        callback();
    },

    tearDown: function (callback) {
        wsServer.close();
        callback();
    },


    'ping test': function(test) {
        var clientsocket = ioclient.connect( 'http://localhost:' + wsServer.getPort() );
        clientsocket.on('ping', function(data){
            test.equal('ok', data.value);
            test.done();
        });

        clientsocket.emit('ping', { pingRequest: '1' });

    },

    'another ping test': function(test) {
        var clientsocket = ioclient.connect( 'http://localhost:' + wsServer.getPort() );
        clientsocket.on('ping', function(data){
            test.equal('ok', data.value);
            test.done();
        });

        clientsocket.emit('ping', { pingRequest: '1' });

    }


});

file test/server.js

function Server() {
    this.port = 3333;
}

Server.prototype.initialize = function () {
    this.create();
}

Server.prototype.getPort= function () {
    return this.port;
}

Server.prototype.addEvent = function (name, fn) {
    this.instance.sockets.on(name, fn);
}

Server.prototype.create = function () {
    var io = require("socket.io").listen(this.port, {'log level': 1});

    //io.sockets.on('connection',);
    this.instance = io;
}

Server.prototype.close = function () {
    this.port ++;
    this.instance.server.close();
}

exports.Server = Server;

Source: (StackOverflow)

Nodeunit test hangs for async db call ORMnomnom

I am trying to write unit test for async db calls. I'm using NodeJS with ORMnomnom package installed as orm db access and nodeunit for unit testing. But it hang for this simple test:

Here is code test\test1.js

modelsdb = require('../model/model_db')

exports['test db'] = function (test) {
  test.expect(1);
  console.log('test db');
  modelsdb.MyTable.objects.all( function (err, data) { 
    test.ok(true, "this assertion should pass"); 
    test.done();
    console.log('test must finish here!');
  });
}

exports.testSomething = function(test){
  console.log('testSomething');
  test.expect(1);
  test.ok(true, "this assertion should pass");
  test.done();
};

When I run this test all assertions passed, I see my messages in console: 'test db' 'test must finish here!' 'testSomething' (means that test.done() reached inside callback function) but test doesn't finish. I need to stop it manually, get: 'Process finished with exit code 1'. If I change to test.ok(false,""), so I get AssertionError but test doesn't finish either. If I remove 'test db' and left only testSomething function - test finished as expected, all assertion passed.

I also try testpilot package which is based on nodeunit. It gives

test1
   FAIL : test db
      an error occurred during test:
         Error: timed out waiting for test

Any suggestions? Thanks.


Source: (StackOverflow)

Running setup code before a test suite in Node Unit

When writing automated system/integration tests, it's common for the first step to run before all of the tests to be "start the server." Since starting a server can be expensive, it is desirable to do this one time, not before each individual test. JUnit has easy functionality for doing this. Is there an equivalent standard pattern in nodeunit? Or does it require hand rolling something?


Source: (StackOverflow)

Use Jasmine to stub JS callbacks based on argument values

I've got a JS method in my node.js app that I want to unit test. It makes several calls to a service method, each time passing that service a callback; the callback accumulates the results.

How can I use Jasmine to stub out the service method so that each time the stub is called, it calls the callback with a response determined by the arguments?

This is (like) the method I'm testing:

function methodUnderTest() {

    var result = [];
    var f = function(response) {result.push(response)};

    service_method(arg1, arg2, f);

    service_method(other1, other2, f);

    // Do something with the results...
}

I want to specify that when service_method is called with arg1 and arg2, the stub will invoke the f callback with a particular response, and when it is called with other1 and other2, it will invoke that same callback with a different particular response.

I'd consider a different framework, too. (I tried Nodeunit, but didn't get it to do what I wanted.)


Source: (StackOverflow)

Overriding functions in other modules in node.js

I'm trying to stub a function with nodeunit in a Node.js app. Here's a simplified version of what I'm trying to do:

In lib/file.js:

var request = require('request');

var myFunc = function(input, callback){
    request(input, function(err, body){
        callback(body);
    });
};

In test/test.file.js:

var file = require('../lib/file');

exports['test myFunc'] = function (test) {
    request = function(options, callback){
        callback('testbody');
    };

    file.myFunc('something', function(err, body){
        test.equal(body, 'testbody');
        test.done();
    });
};

It seems like I'm not overriding request properly, because when I try to run the test, the actual non-stub request is getting called, but I can't figure out what the correct way to do it is.

EDIT:

To expand on Ilya's answer below, with my example above.

in lib/file/js:

module.exports = function(requestParam){
    return {
        myFunc: function(input, callback){
            requestParam(input, function(err, body){
                callback(body);
            });
        }
    }
}

Then in test/test.file.js:

var fakeRequestFunc = function(input, callback){
// fake request function
}

var file = require('../lib/file')(fakeRequestFunc)(
//test stuff
}

Source: (StackOverflow)

How do I get an asynchronous result back with node unit and mongoose?

How do I get an asynchronous result back in nodeunit and mongoose? I've tried the following code and it seems to hang on the database callback never returning a result or err.

mongoose = require "mongoose"
models = require "../Services/models"
Task = models.Task

module.exports =
setUp: (callback) ->
    try
        @db = mongoose.connect "myConnString"
        console.log 'Started connection, waiting for it to open'


        @db.connection.on 'open', () ->
            console.log 'Opened connection'
            callback()
    catch err
          console.log 'Setting up failed:', err.message
tearDown: (callback) ->
    console.log 'In tearDown'
    try
        console.log 'Closing connection'
        @db.disconnect()
        callback()
    catch err
        console.log 'Tearing down failed:', err.message
"get tasks" : (test) ->
    console.log 'running first test'
    Task.find {}, (err, result) ->
        if not err
            console.log 'results' + result
            test.ok(result)
        else
            console.log 'error' + err   
        test.ifError(err)
        test.done()

Source: (StackOverflow)

why is my nodeunit test of mongodb not finishing?

I am writing nodeunit tests for operations around a mongodb. When I execute my test with nodeunit (nodeunit testname.js), the test runs through and goes green but the nodeunit command line doesn't return (I need to hit ctrl-c).

What am I doing wrong? Do I need to close my db connection or the server or is my test wrong?

Here is a cutdown sample test.

process.env.NODE_ENV = 'test';
var testCase = require('/usr/local/share/npm/lib/node_modules/nodeunit').testCase; 
exports.groupOne = testCase({
    tearDown: function groupOneTearDown(cb) {       
    var mongo = require('mongodb'), DBServer = mongo.Server, Db = mongo.Db;
    var dbServer = new DBServer('localhost', 27017, {auto_reconnect: true});
    var db = new Db('myDB', dbServer, {safe:false});

    db.collection('myCollection', function(err, collectionitems) {
            collectionitems.remove({Id:'test'});    //cleanup any test objects
        }); 

    cb();
},
aTest: function(Assert){
    Assert.strictEqual(true,true,'all is well');
    Assert.done();
}
});

Michael


Source: (StackOverflow)

How to create a data driven test in Node.js

In Node.js unit tests, what is the way to create data driven unit tests?

For Example, I've a common function / method, which I want to re-use in multiple unit tests with different sets of data. I tried looking into nodeunit, vows, whiskey, qunit, expresso; But I wasn't able to figure out a way to achieve this functionality.

I was not looking at calling the function literally in multiple tests, but rather use the common method in a loop to pick up the data in each iteration and execute it, as a unittest

The reason for this is, I've atleast 1000 rows of parameterized data, for which I want to write unittest. Obviously I cannot go on writing 1000 unittests physically.

Anyone could you please point me a way to achieve the above.


Source: (StackOverflow)

Possible to tell nodeunit not to finish a particular test until test.done() is called?

I am doing some async testing with nodeunit and I was wondering whether it is possible to tell nodeunit to not terminate test cases until test.done is called.

Basically this is how my test cases looks like right now:

exports.basic = testCase({

  setUp: function (callback) {
    this.ws = new WrappedServer();
    this.ws.run(PORT);
    callback();
  },

  tearDown: function (callback) {
    callback();
  },

  testFoo: function(test) { 
    var socket = ioClient.connect(URL);
    socket.emit('PING', 1, 1);
    socket.on('PONG', function() { 
      // do some assertion of course
      test.done();
    }); 
  }
});

The problem now is that PONG is not sent back quick enough for the test code to be executed. Any ideas?


Source: (StackOverflow)

How to test a Grunt task? Understanding and best practices

I'm a bit stuck with understanding how to write complicated Gruntfile.js and use it with tests. Am I using Grunt in a right way? I would like to ask community for help and contribute in an other way.

I'm writing a new task for Grunt and want to roll it out for wide audience on Github and npm. I want to make automated testing for this task (and I want to learn how to do it properly!).

I want to test different options combinations (about 15 by now). So, I should multiple times:

  • run cleanup
  • run my task with next options set
  • run tests and pass options object to the test

Some non-working code to look at for better understanding:

Gruntfile:

grunt.initConfig({

    test_my_task: {
        testBasic: {
            options: {
                 //first set
            }
        },
        testIgnore: {
            options: {
                //another set
            }
        },

        //...
    }

    clean: {
        tests: ['tmp'] // mmm... clean test directory
    },

    // mmm... unit tests.
    nodeunit: {
        tests: ['test/*.js']  //tests code is in 'tests/' dir
    }
});

grunt.registerTask('test', ['test_my_task']);

I know how to check if tmp/ folder is in desired state when options object given.

The problem is putting things together.

I would ask just for template code as an answer, npo need to put working example.

PS: you can propose another testing tool, nodeunit is not a must.

PPS: crap, I could have written this in plain javascript by now! Maybe I'm doing wrong that I want to put Grunt into the unit tests? But I want to test how my task works in real environment with different options passed from Grunt...


Source: (StackOverflow)

Structure for unit testing on node.js with mongoose

I've been developing with node.js for months but now I'm starting a new project and I'd like to know how to structure the app.

My problem comes when talking about unit testing. I will use nodeunit to write unit tests.

Also I'm using express to define my REST routes.

I was thinking about writing my code that access databases in two "separate" files (They will be more, obviously, but I'm just trying to simplify the code). There will be the routes code.

var mongoose = require('mongoose')
 , itemsService = require('./../../lib/services/items-service');

// GET '/items'
exports.list = function(req, res) {
    itemsService.findAll({
        start: req.query.start,
        size: req.query.size,
        cb: function(offers) {
            res.json(offers);
        }
   });  
  };

And, as I'm using there, an item service used just to access data layer. I'm doing this to test only data access layer on unit testing. It'll be something like this:

var mongoose = require('mongoose')
  , Item = require('./../mongoose-models').Item;

exports.findAll = function(options) {
    var query = Offer
        .find({});
    if (options.start && options.size) {
        query
            .limit(size)
            .skip(start)
    }
    query.exec(function(err, offers) {
        if (!err) {
                options.cb(offers);
            }
    })
};

This way I can check with unit testing if it works correctly and I can use this code everywhere I want. The only thing I'm not sure if it's been correctly done is the way I pass a callback function to use returned value.

What do you think?

Thanks!


Source: (StackOverflow)

Why nodejs test case with nodeunit keep loading in webstorm after successfully passed the test cases?

I am working on nodejs project. And I am using nodeunit npm module to test my server-side codebase. I am using Webstorm as an editor for writing my codes and also testing the server-side code with the help of nodeunit module.

Everything is working perfectly, my test cases passed correctly but the test cases progress is keep loading in Webstorm status panel. I have manually to stop that each time. Does anybody have any idea on this?


Source: (StackOverflow)