Carlos Baraza Carlos Baraza - 11 days ago 6
Javascript Question

Mocha test is not waiting for Publication/Subscription

Stack



Using Mocha + Velocity (0.5.3) for Meteor client-side integration tests. Let's assume that I have autopublish package installed.

Problem



If a document on the MongoDB was inserted from the server, the client-side mocha tests will not wait for the subscription to synchronise, causing the assertion to fail.

Code example



Server-side
Accounts.onCreateUser
hook:

Accounts.onCreateUser(function (options, user) {
Profiles.insert({
'userId': user._id,
'profileName': options.username
});

return user;
});


Client-side Mocha Test:

beforeEach(function (done) {
Accounts.createUser({
'username' : 'cucumber',
'email' : 'cucumber@cucumber.com',
'password' : 'cucumber' //encrypted automatically
});

Meteor.loginWithPassword('cucumber@cucumber.com', 'cucumber');
Meteor.flush();
done();
});

describe("Profile", function () {

it("is created already when user sign up", function(){
chai.assert.equal(Profiles.find({}).count(), 1);
});

});


Question



How could I make Mocha wait for my profile document to make its way to the client avoiding the Mocha timeout (created from the server)?

Answer

You can reactively wait for the documents. Mocha has a timeout, so it would stop automatically after some time if the documents are not created.

it("is created already when user signs up", function(done){
  Tracker.autorun(function (computation) {
    var doc = Profiles.findOne({userId: Meteor.userId()});
    if (doc) {
      computation.stop();
      chai.assert.propertyVal(doc, 'profileName', 'cucumber');
      done();
    }
  });
});
Comments