0

I am creating unit tests for nodejs app using "tape". When I run tests, the process gets blocked forever. When I dug deeper, I found that if I run "nodejs mainapp.js" the process doesn't end. That's also blocking running of unit tests.

Looks like nodejs process will not end if there are events registered. In my case, creating a mongo or redis connection or use of node modules such as "node-cache" results into this. It's hard to imagine that all such modules can be avoided. Any suggestion on how to get around the problem. My test case is really simple so there are on issues there.

By the way, I have verified nodejs doesn't get blocked due to http.listen. Someone could argue about using mockups, I am not looking to do that.

test('dummy test', function(t) {
  t.equal('hello world', 'hello world', 'Yes hello world = hellow world');
  t.end();
});
user2080367
  • 73
  • 1
  • 5
  • Have you tried performing a proper cleanup at the end of your tests, like closing network connections to databases, etc? Node doesn't know when you're done with such connections unless you tell it to. – robertklep Nov 29 '15 at 10:53
  • In the application, no I don't close connections. I don't create any connections in test code. – user2080367 Dec 02 '15 at 01:59
  • 1
    Any connections created would stop Node from exiting, which is normal behaviour. So unless you close the connections (either that, or create mock connections), Node will not know when you're done with them and the process won't exit once your tests have run. – robertklep Dec 02 '15 at 07:53
  • Thanks @robertklep. I had to force close all network connections and other modules which registers to some kind of event such as node-cache. Now it works fine. – user2080367 Dec 03 '15 at 07:01

1 Answers1

2

The main cause of tape processes keeping alive are MongoDB connections not closed. The easiest way to close a connection when all tests ends, is to create a blank test with instructions to close the MongoDB connection. The following is an example, in this case using Mongoose:

var test = require('tape');
var mongoose = require('mongoose');

test('test', function (t) {
    t.pass('Example');
    t.end();
});

test('finish', function (t) {
    mongoose.disconnect();
    t.pass('closing db connection');
    t.end();
});

if the problem is indeed a MongoDB connection, a more proper way to deal with it would be using test.onFinish(fn) according to documentation:

The onFinish hook will get invoked when ALL tape tests have finished right before tape is about to print the test summary.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Matheus Portillo
  • 187
  • 3
  • 10