灰烬验收测试 - 异步副作用错误

时间:2017-01-18 23:03:55

标签: ember.js qunit acceptance-testing ember-testing

试图在Ember中进行验收测试:

test('successful login', (assert) => {

  Ember.run(() => {
    visit('/signin');
    fillIn('#email', 'validemail@server.com');
    fillIn('#password', 'password');
    click(':submit');

    andThen(function() {
      assert.equal(currentURL(), '/');
    });
  });
});

偶尔(并且看似随机)会产生错误:

“全局错误:错误:断言失败:您已打开测试模式,禁用了运行循环的自动运行。您需要在运行中包装任何带有异步副作用的代码......”

我能够获得一个正常工作的版本:

test('successful login', (assert) => {
  const done = assert.async();

  Ember.run(() => {
    visit('/signin').then(() => {
      fillIn('#email', 'isaac@silverorange.com').then(() => {
        fillIn('#password', 'keen').then(() => {
          click(':submit').then(() => {
            assert.equal(currentURL(), '/');
            done();
          });
        });
      });
    });
  });
});

但是,如果我包含使用相同路由的第二个测试(对于不成功的登录),其中一个几乎总是以上面列出的错误结束。

我想知道我对运行循环,Ember.run以及如何使用异步行为进行测试并不了解。任何有关良好资源的帮助或指示都将不胜感激!

2 个答案:

答案 0 :(得分:0)

根据the guide,您的代码应该是这样的:

test('successful login', (assert) => {
  visit('/signin');
  fillIn('#email', 'validemail@server.com');
  fillIn('#password', 'password');
  click(':submit');

  andThen(function() {
    assert.equal(currentURL(), '/');
  });
});

您不需要在案件中添加Ember.run

答案 1 :(得分:0)

最常见的情况是,当您在应用程序中执行某些操作(异步)并且没有为Ember正确包装时(包括我的意思是在Ember运行循环中执行),就会出现此问题。

最常见的原因

  1. 您直接或使用jQuery将事件处理程序附加到DOM,而不包含与Ember.run中的Ember应用程序的交互()
  2. 您直接或使用jQuery执行了XHR(异步),而没有在Ember.run()的回调中包装与Ember应用程序的交互
  3. 通用修复

    当你导致在runloop(XHR回调或事件处理程序)之外与你的应用程序交互的代码执行时,用Ember.run()包装该代码。

    活动:

    Ember.$('div').on('mouseover',function() {
        Ember.run(function() {
           // Interaction with application
        });
    });
    

    XHR / AJAX:

    Ember.$.ajax({
        success: function() {
            Ember.run(function() {
               // Interaction with application
            });
        }
    });
    

    最佳做法

    1. 使用DOM事件时:
    2. 当你想做AJAX / XHR时使用ember-ajax(https://github.com/ember-cli/ember-ajax