【问题标题】:Mocha test is not waiting for Publication/SubscriptionMocha 测试不等待发布/订阅
【发布时间】:2015-04-30 12:01:20
【问题描述】:

堆栈

使用 Mocha + Velocity (0.5.3) 进行 Meteor 客户端集成测试。假设我安装了 autopublish 包。

问题

如果 MongoDB 上的文档是从服务器插入的,客户端 mocha 测试将不会等待订阅同步,从而导致断言失败。

代码示例

服务器端Accounts.onCreateUser钩子:

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

  return user;
});

客户端摩卡测试:

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

});

问题

如何让 Mocha 等待我的个人资料文档到达客户端,避免 Mocha 超时(从服务器创建)?

【问题讨论】:

    标签: javascript testing meteor mocha.js velocity


    【解决方案1】:

    您可以被动地等待文件。 Mocha 有一个超时,所以如果文档没有创建,它会在一段时间后自动停止。

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

    【讨论】:

    • 太棒了,这真的很有帮助。感谢 Sanjo 的快速响应!
    【解决方案2】:

    Accounts.createUser 有一个可选的回调,只需在这个回调中调用 done 函数,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 2017-06-15
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      相关资源
      最近更新 更多