Mocha test is not waiting for Publication/Subscrip

2019-08-15 01:59发布

问题:

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)?

回答1:

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


回答2:

Accounts.createUser has an optional callback, just call the done function within this callback as in:

beforeEach(function (done) {
    Accounts.createUser({
        'username'  : 'cucumber',
        'email'     : 'cucumber@cucumber.com',
        'password'  : 'cucumber' //encrypted automatically
    }, () => {
        // Automatically logs you in
        done();
    });
});
describe('Profile', function () {
    it('is created already when user sign up', function () {
        chai.assert.equal(Profiles.find({}).count(), 1);
    });
});