【问题标题】:Test state change of a reflux store with mocha使用 mocha 测试回流商店的状态变化
【发布时间】:2015-11-09 02:18:02
【问题描述】:

我正在针对 Reflux 商店编写 mocha 测试,以验证某个操作是否会导致商店中的状态发生变化。代码缩小版如下:

商店:

var AppStore = Reflux.createStore({
  init: function () {
    this.foo = false;
  },
  listenables: [AppActions],
  onFooAction: function() {
    this.foo = !this.foo;
    this.trigger({action: "foo-ed"});
  };
});

行动:

var AppActions = Reflux.createActions([
  "fooAction"
]);

测试:

it("toggles foo", function () {
  expect(AppStore.foo).to.equal(false);

  AppStore.listenables[0].fooAction();

  expect(AppStore.foo).to.equal(true);
});

但是,第二个断言 (expect(AppStore.foo).to.equal(true);) 未能表明 foo 仍然是错误的。

通过在onFooAction 方法中执行console.log,我验证了该方法实际上已被触发并且this.foo 正在被切换。

我在这里缺少什么基本的东西:概念上还是其他方面?我真诚地希望这不是时间问题!

【问题讨论】:

    标签: javascript unit-testing mocha.js refluxjs


    【解决方案1】:

    Action 发出商店监听的事件。基本上,您的测试运行得太快了。

    通常,在我的测试中,我假设 Reflux 会做正确的事情,我会直接调用监听器函数。您需要添加更多断言以确保 Reflux 连接正确。

    it("is configured", function () {
      expect(AppStore.listenables).to.include(AppActions);
      expect(AppActions.fooAction).to.be.a('function');
    });
    
    it("toggles foo", function () {
      expect(AppStore.foo).to.equal(false);
    
      AppStore.onFooAction();
    
      expect(AppStore.foo).to.equal(true);
    });
    

    另一种测试方法是使用超时,但是当我在测试中设置超时时我觉得很脏。

    it("toggles foo", function (done) {
      expect(AppStore.foo).to.equal(false);
    
      AppStore.listenables[0].fooAction();
    
      setTimeout(function () {
        try {
          expect(AppStore.foo).to.equal(true);
          done();
        } catch (e) {
          done(e);
        }
      }, 15);
    });
    

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2018-01-23
      • 2015-06-27
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      相关资源
      最近更新 更多