gpt4 book ai didi

jquery - 使用 qUnit 测试 .animate 的更好方法

转载 作者:行者123 更新时间:2023-12-01 01:24:18 26 4
gpt4 key购买 nike

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

<强> full fiddle

测试在除 2.x (edge) 之外的所有 jQuery 版本上均失败

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

增加超时持续时间足以使测试通过,因此我认为动画在探测左侧属性之前尚未完成。

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

最佳答案

您需要重构您的测试以及 moveLeft 方法。您当前正在执行的操作是调用 .animate (我推测,moveLeft.animate 的包装器),然后告诉 qUnit 等待 101检查元素左侧位置之前的毫秒。正如您已经指出的,这不是一种非常可靠的测试方法!

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

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

然后您将这个回调传递给moveLeft函数中的.animate

例如,您的通话现在如下所示:

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

Fiddle

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

关于jquery - 使用 qUnit 测试 .animate 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18818250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com