Node.js:测试永远不会调用回调

时间:2012-08-10 15:38:37

标签: node.js testing asynchronous

我有一些异步循环的代码,从数据库读取并发出它找到的任何新记录:

var foo = new EventEmitter();

foo.stopped = false;

function run() {
    readSomeData(function(err, data) {
        if (foo.stopped) return;

        if (err) foo.emit('error', err);
        if (data) foo.emit('data', data);

        run();
    });
}

run();

测试停止时不再发出数据的最佳方法是什么? 以下是一次尝试。有没有办法重构代码以避免使用 setTimeout?这个测试看起来一般都很脆弱。

it('does not emit data when stopped', function(done) {
    var count = 0;

    foo.on('error', done);

    foo.on('data', function(data) {
        count++;

        if (count === 2) next();
        if (count > 2) done(new Error('Data should not have been emitted'));
    });

    // We'll know that this data has been written when the `data` callback
    // is called twice
    writeSomeData(mydata1, function(err) {
        if (err) done(err);
    });
    writeSomeData(mydata2, function(err) {
        if (err) done(err);
    });

    function next() {
        foo.stopped = true;

        writeSomeData(mydata3, function(err) {
            if (err) return done(err);

            // Data has been written but would it have been read yet
            // if `foo` was not stopped?  Perhaps not.  Wait a little bit
            // to ensure we don't get a false positive test.

            setTimeout(done, 1000);
        });
    }
});

0 个答案:

没有答案