Javascript:同步代码
我正在编写一个验证脚本,使用JQuery设置字段,然后验证它们对JSON blob的持久性。对于文本字段没有问题,但日历需要一些等待时间,我遇到了麻烦。注意:我没有使用Selenium,因为我的目标是创建一个更快的替代品 示例代码: //setCalendars是一个jQuery包装器Javascript:同步代码,javascript,jquery,automation,Javascript,Jquery,Automation,我正在编写一个验证脚本,使用JQuery设置字段,然后验证它们对JSON blob的持久性。对于文本字段没有问题,但日历需要一些等待时间,我遇到了麻烦。注意:我没有使用Selenium,因为我的目标是创建一个更快的替代品 示例代码: //setCalendars是一个jQuery包装器 test1 = function() { loadPage(); setTimeout(function() { setCalendars(fromDate, toDate); s
test1 = function()
{
loadPage();
setTimeout(function()
{
setCalendars(fromDate, toDate);
setTimeout(function()
{
assertEqual(fromDate, blob.fromDate);
assertEqual(toDate, blob.toDate);
}
, INTERVAL);
}
, INTERVAL);
}
问题是test2和test3在设置日历字段和创建混乱之前开始执行
请告知我强烈推荐Tim Caswell的库,它是专门为序列化回调执行而设计的 您上面的代码将变成如下内容:
test1 = function()
{
Step(
loadPage,
function () {
setCalendars(fromDate, toDate);
this(); // triggers the next step
},
function () {
assertEqual(fromDate, blob.fromDate);
assertEqual(toDate, blob.toDate);
}
)
}
通过步骤
您可以仔细控制何时执行
如果将代码修改为在每个步骤完成时具有回调,则可以将代码修改为以下内容:
test1 = function()
{
Step(
loadPage(this),
function () {
setCalendars(fromDate, toDate, this);
},
function () {
assertEqual(fromDate, blob.fromDate);
assertEqual(toDate, blob.toDate);
}
)
}
请注意,在步骤
的上下文中,此
是触发序列中下一个“步骤”的回调
希望有帮助,Aaron如果您可以使用某种回调机制,而不是依赖计时器,那么在setCalendars中共享代码会更好