如何让Mink Selenium 2 Driver等待页面加载Behat

问题描述 投票:4回答:4

我正在从Behat 2.x系列升级到Behat 3.x系列。在之前的版本中,我可以加载Selenium 1驱动程序,该驱动程序连接到PhantomJS以执行测试。当我这样做时,我能够挂钩一个名为waitForPageToLoad()的函数。

此功能由php-selenium(来自AlexandreSalomé)提供。它挂钩到selenium并用同一个名字调用驱动程序动作。这非常适合确保Selenium等待页面加载。至少在达到超时之前。它使测试变得更快。

问题是Selenium 1驱动程序与Behat 3.x不兼容。看起来它已经被抛弃,我在Selenium 2驱动程序中看不到Mink的功能。

有没有人知道如何使用Behat 3.x和Selenium 2?

php selenium phantomjs behat mink
4个回答
8
投票

使用Selenium(或任何其他驱动程序),我从来不必担心页面是否已加载,但有一个例外:如果页面完成加载,则通过AJAX加载更多内容。

要处理此问题,您可以使用Behat手册中记录的旋转功能。

http://docs.behat.org/en/v2.5/cookbook/using_spin_functions.html

这样做的好处是:

  • 它不需要你使用selenium驱动程序(例如,如果你想要速度超过外观你可以使用PhantomJS)。
  • 如果你停止使用jQuery并切换到其他东西(例如Angular的$ httpProvider),它不会破坏

我不会使用他们的,后面的痕迹是破碎的,谁想要在支票之间等待一秒钟。 :)

试试这个:

假设您正在使用Mink Context(感谢Mick),您可以每隔一秒左右检查一次页面,直到所需的文本出现或消失,或者给定的超时已过期,在这种情况下我们假设失败。

/**
 * @When I wait for :text to appear
 * @Then I should see :text appear
 * @param $text
 * @throws \Exception
 */
public function iWaitForTextToAppear($text)
{
    $this->spin(function(FeatureContext $context) use ($text) {
        try {
            $context->assertPageContainsText($text);
            return true;
        }
        catch(ResponseTextException $e) {
            // NOOP
        }
        return false;
    });
}


/**
 * @When I wait for :text to disappear
 * @Then I should see :text disappear
 * @param $text
 * @throws \Exception
 */
public function iWaitForTextToDisappear($text)
{
    $this->spin(function(FeatureContext $context) use ($text) {
        try {
            $context->assertPageContainsText($text);
        }
        catch(ResponseTextException $e) {
            return true;
        }
        return false;
    });
}

/**
 * Based on Behat's own example
 * @see http://docs.behat.org/en/v2.5/cookbook/using_spin_functions.html#adding-a-timeout
 * @param $lambda
 * @param int $wait
 * @throws \Exception
 */
public function spin($lambda, $wait = 60)
{
    $time = time();
    $stopTime = $time + $wait;
    while (time() < $stopTime)
    {
        try {
            if ($lambda($this)) {
                return;
            }
        } catch (\Exception $e) {
            // do nothing
        }

        usleep(250000);
    }

    throw new \Exception("Spin function timed out after {$wait} seconds");
}

5
投票

Selenium2现在具有wait($timeout, $condition)功能。

您可以像以下一样使用它:

/**
 * @Then /^I wait for the ajax response$/
 */
public function iWaitForTheAjaxResponse()
{
    $this->getSession()->wait(5000, '(0 === jQuery.active)');
}

您可以测试的其他条件是:

  • 页面上某个元素的外观
  • DOM完成加载

硒网站documentation概述了这一变化的原因


0
投票

为了帮助别人,我在FeatureContext.php中添加了这个方法:

 /**
 * @Then I wait :sec
 */
public function wait($sec)
{
    sleep($sec);
}

这是工作威尔


0
投票
/**
* @Then /^I wait for the ajax response$/
*/
public function iWaitForTheAjaxResponse()
{
   $this->getSession()->wait(5000, '(0 === jQuery.active)');
}

它正在工作

© www.soinside.com 2019 - 2024. All rights reserved.