3

了解 TDD 我编写了一个简单的测试套件,用于将dom元素移动到左侧。

我测试动画我需要等待它们完成。我不想使用 Promise,因为它感觉就像猴子修补,我最终使用了 qUnit 示例表单:

test("move 50", function () {
   //Creates an element for testing and attaches to document
   var el = appendToTest(); 
   ok(el.css('left') == "auto", "element 0");
   stop();
   moveLeft(el, 50, 100);
   setTimeout(function () {
     equal(el.css("left"), "50px");
     start();
  }, 101);//Timeout duration
});

全小提琴

测试在所有 jQuery 版本上都失败了,但是2.x (edge)

failed
Expected:   
"50px"
Result:     
"49.69220733642578px"
Diff:   
"50px" "49.69220733642578px" 

增加超时持续时间足以使测试通过,所以我认为动画在被探测到 left 属性之前没有完成。

但这似乎不对。不得不猜测要等多久。有一个更好的方法吗?

4

2 回答 2

2

您需要重新构建您的测试和方法moveLeft。您当前正在做的是调用.animate(我认为moveLeft是 包装器.animate),然后告诉 qUnit 在检查元素的左侧位置之前等待 101 毫秒。正如您已经注意到的,这不是一种非常可靠的测试方法!

相反,您需要利用在完成执行时.animate调用回调函数的能力;以便您修改moveLeft函数以接受此回调,您将其定义为

function() {equal(el.css("left"), "50px");start();}

然后将此回调传递给.animate您的moveLeft函数

例如,您的电话现在看起来像这样:

//tells qUnit to expect that one assertion will happen.
//this will mean that your test will also fail if moveLeft doesn't invoke the callback.
      expect(1); 
//define the calback function
      var callback = function(){equal(el.css("left"), "50px");start();}
//execute the test:
       moveLeft(el, 50, 100,callback);

小提琴

作为奖励,您现在拥有一个更灵活的moveLeft函数,可以接受任意回调。\o/

于 2013-09-17T15:25:50.807 回答
0

实际上,有一个更好的方法 - 使用 Sinon 的假计时器 - http://sinonjs.org/docs/#clock

  1. 在设置中初始化假计时器:

    setup: function () { this.clock = sinon.useFakeTimers(); }

  2. 在测试中调用moveLeft()函数后,将假计时器设置为 100 毫秒:

    this.clock.tick(100);

  3. 现在您可以在不使用异步测试的情况下立即测试动画结果:

    equal(el.css("left"), "50px");

于 2014-04-03T10:04:20.133 回答