Search code examples
node.jsunit-testingintegration-testingnodeunit

nodeunit fail to exit from my asynchronous tests


Whenever I run my nodeunit test in IDE or console, it run well but fail to exit. Help me please with it!

var store = require('../lib/db');
var list = require('../source/models/mock_deals');
var logger = require('../lib/logging').logger;

exports.setUp = function(done){
    logger.info('start test...');
    done();
};
exports.tearDown = function(done){
    logger.info('end test...');
    done();
};

exports.testInsertDeal = function(test){
    var length = list.length;
    test.equals(length, 2);
    store.mongodb.open(function(err,db){
        if(err){
            logger.error(err);
            return;
        }
        logger.info("mongodb is connected!");

        db.collection('deals',function(err,collection){
            for(var i=0; i<length; i++){
                var item = list[i];
                collection.insert(item, function(err, result){
                    if(err){
                        logger.error('Fail to insert document deal [' + item.id + ']');
                        return;
                    }
                    logger.info( 'index ' + i + ' : ' +JSON.stringify(item) );
                });
            }
        });
        test.expect(1);
    });
    test.done();
};

Solution

  • I changed to use mongoose instead of mongodb. test still could not exit automatically.

    But when I disconnected mongoose in test.tearDown method in my nodeunit test. the test existed correctly.

    Add below in you test:

    exports.tearDown = function(done){
        mongoose.disconnect(function(err){
            if(err) {
                logger.error(err);
                return;
            }
            logger.info('mongoose is disconnected');
        });
        done();
    };
    

    And more, If I use log4js for logging in my test and configure log4js with reloadSecs: 500 , test will not exist either. After I set reloadSecs to 0, then test exists well. So we need to configure logging.json with option reloadSecs: 0

    To summarize: we need to make sure there are no working parts there after all test methods are done. then test will exist correctly.