【问题标题】:nodeunit fail to exit from my asynchronous testsnodeunit 无法退出我的异步测试
【发布时间】:2013-08-02 07:36:59
【问题描述】:

每当我在 IDE 或控制台中运行我的 nodeunit 测试时,它运行良好但无法退出。请帮帮我!

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();
};

【问题讨论】:

    标签: node.js unit-testing integration-testing nodeunit


    【解决方案1】:

    如果您知道程序应该何时退出,您可以简单地使用以下代码行退出:

    process.exit(0);
    

    其中 0 是程序的返回码。

    现在这并不能真正解决问题。可能有一个仍在等待的回叫或一个仍然处于活动状态的连接,以使您的程序保持正常运行,而您在此处发布的代码中未显示。如果您不想找到它,只需使用 process.exit。如果你真的想找到它,你将不得不再挖一些。我从未使用过nodeunit,但我使用过其他节点库,这些库会在其内部工作中留下一些东西,从而阻止程序退出。在这些情况下,我通常不想费力地翻阅其他人的源代码来找出发生了什么,所以我只是执行上述 process.exit 调用。

    这至少应该给你一个选择。

    【讨论】:

    • 你的回答提醒了我。测试完成后,我的测试中仍有一些工作代码。
    【解决方案2】:

    我改为使用 mongoose 而不是 mongodb。测试仍然无法自动退出。

    但是当我在我的 nodeunit 测试中以test.tearDown 方法断开猫鼬时。测试正确存在。

    在您的测试中添加以下内容:

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

    此外,如果我使用 log4js 登录我的测试并使用 reloadSecs: 500 配置 log4js ,测试也将不存在。在我将reloadSecs 设置为 0 之后,测试就存在了。所以我们需要配置 logging.json 选项reloadSecs: 0

    总而言之:我们需要确保在所有测试方法完成后那里没有工作部件。那么测试将正确存在。

    【讨论】:

    • 在回调中调用 done() 来断开连接不是更好吗?然后你就可以确定断开连接完成了。
    猜你喜欢
    • 2015-04-25
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    相关资源
    最近更新 更多