mardi 30 juin 2015

Test: wait for event listeners to finish

I would like to know how to wait for event listeners to finish before making an assertion in a test.

I am testing a function ItemFetcher.fetch() that parses rss feeds and creates a document. It uses node-feedparser in this manner:

feedparser.on('readable', function() {
  // read the stream and write to the database
});

In my test suite using Mocha, Chai, and Velocity, I am testing that a document is created after calling ItemFetcher.fetch().

ItemFetcher.fetch();

expect(Items.find().count()).to.equal(1);

Somehow, this fails because the actual value is 0. However, when I add another random code in between, giving a small delay before my assertion, the test passes.

ItemFetcher.fetch();

expect(Something).to.equal(something); // random assertion
expect(Items.find().count()).to.equal(1);

I think there is a race condition in my test because I am using event listener. How can I wait until ItemFetcher.fetch() is done processing the events before my assertion?

I tried to modify the ItemFetcher.fetch() to take a callback, and move my assertion inside the callback and call done() to test async in Mocha, but it did not solve the problem.

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire