非同期にループし、データベースから読み取り、見つかった新しいレコードを発行するコードがいくつかあります。
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();
停止時にこれ以上データが発行されないことをテストする最良の方法は何ですか? 以下は 1 つの試みです。の使用を避けるためにコードを再構築する方法はあり
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);
});
}
});