PHPUnit+Selenium 2:ajax加载操作


PHPUnit + Selenium 2: Action on ajax load

在测试期间,我需要执行以下操作:

  • 点击按钮,导致ajax请求,然后重定向
  • 检查用户是否已重定向到正确的页面

我的代码:

$this->byId('reg_email')->value('test@example.com');
$this->byId('reg_password')->value('seecret');
// No form here, so i can't just call submit()
// This click invokes ajax request
$this->byId('reg_submit')->click();
// Check page content (this page should appear after redirect)
$msg = $this->byCssSelector('h1')->text();
$this->assertEquals('Welcome!', $msg);

问题

  • 点击后立即进行消息检查,而不是在ajax请求和页面重定向之前

解决方案,我不喜欢:

  • 在内容检查之前添加sleep(3);

我不喜欢它,因为:

  • 这太傻了
  • 如果是快速响应,我会浪费时间,如果是长请求,我会在ajax请求完成之前进行内容检查

我想知道,有没有什么方法可以跟踪ajax请求+刷新并及时检查内容?

我的设置:

  • PHP 5.4、5.5也可用
  • PHPUnit 3.8
  • PHPUnit 1.3.1的硒RC集成
  • Selenium服务器单机版2.33.0
  • Windows 7 x64
  • JRE 7

好的,有一种解决方案,我不是很喜欢,但它是有而不是没有。

这个想法是使用更智能的"睡眠",有一种方法waitUntil(),它以毫秒为单位使用anonymous functiontimeout。它的作用是在循环中运行这个传递的函数,直到超时或函数返回True。因此,您可以运行一些东西并等待上下文更改:

$this->waitUntil(function () {
    if ($this->byCssSelector('h1')) {
        return true;
    }
    return null;
}, 5000);

如果有人能提供更好的解决方案,我仍然会很高兴。

嗯,我不确定它是否对你有用,但你可以尝试使用这个:

$this->timeouts()->implicitWait(20000);