如何使用sinon.useFakeTimers进行余烬测试(接受)?

时间:2015-04-12 19:44:23

标签: ember.js sinon ember-testing

我已经成功地使用sinon时钟帮助编写了ember中的单元级别测试,但验收测试似乎总是一个问题。

例如,在我的路线中,我打算在我做某事之前等待5秒

export default Ember.Route.extend({
    model: function() {
        setTimeout(Ember.run.bind(this, function() {
            //after the timeout do something like transition to another route
        }), 5000);
    }
});

在ember测试中我做了一个简单的访问,断言currentURL()是好的,然后做一个clock.tick(5001)w / sinon ...然后断言定时器完成并且某些状态被设置/ etc

我意识到sinon和ember run循环似乎并不能很好地结合在一起,但我很好奇其他人在高级别用于测试这样的计时器(非单元测试/没有硒或睡眠黑客)。

如果需要稍后运行,你会如何重复下面的(不正确的)测试以使用clock.tick?

test("sinon and ember play nice", function(assert) {
    var clock = sinon.useFakeTimers();
    visit("/");
    andThen(function() {
        assert.equal(currentURL(), "/");
    });
    clock.tick(5001);
    andThen(function() {
        assert.equal(currentURL(), "/the-transition-url");
    });
});

1 个答案:

答案 0 :(得分:2)

我认为在所有情况下sinon.useFakeTimers()都会破坏异步和同步助手(在本例中为andThen())。

我在类似的情况下测试了类似的东西:

test("sinon and ember play nice", function(assert) {
  const clock = sinon.useFakeTimers();
  visit('/');
  clock.tick(0); // this for simulating rendering right now
  assert.equal(currentURL(), '/');
  clock.tick(5100);
  assert.equal(currentURL(), '/the-transition-url');
  clock.restore();
});

p.s。:经过大量的异步助手测试后,看起来像ember测试框架上的异步实现是基于传递的时间。作为副作用,在andThen()clock.tick(0);之前不会执行clock.tick(50);

p.s.2:看起来有关于stackoverflow相关Is there a way to run Ember.Testing acceptance tests with fake timers?以及最新版本(2.9和2.10)的另一个问题,以及qunit的升级,当前代码需要更多调整