如何让behat在填充之前等待元素显示在屏幕上?

问题描述 投票:2回答:3

当我点击一个按钮时,会打开一个带有表单的新页面,我需要在该页面上填写一个字段。

但是,只要页面开始加载,就会尝试填充尚未加载的字段。

我想在尝试填充之前等待显示字段的隐式等待。

   /**
    * @Given que preencho corretamente os campos da tela
    */
   public function quePreenchoCorretamenteOsCamposDaTela()
   {
    $faker = Faker\Factory::create();
    $this->getPage()->findField('voucher_subject')->setValue($faker->text);
    $this->getPage()->findField('voucher_nameRecipient')->setValue($faker->name);
   }

有人能帮帮我吗?

php testing bdd behat mink
3个回答
1
投票

你可以使用旋转功能:

trait FeatureContextHelper
{
    public function spin (callable $lambda, $wait = 5)
    {
        $lastErrorMessage = '';

        for ($i = 0; $i < $wait; $i++) {
            try {
                if ($lambda($this)) {
                    return true;
                }
            } catch (Exception $e) {
                // do nothing
                $lastErrorMessage = $e->getMessage();
            }

            sleep(1);
        }


        throw new ElementNotVisible('The element is not visible ' . $lastErrorMessage);
    }
}

然后在你的上下文中:

class FeatureContext extends MinkContext
{
    use FeatureContextHelper;

    /**
     * @Given que preencho corretamente os campos da tela
     */
     public function quePreenchoCorretamenteOsCamposDaTela()
     {
         $this->spin(function ($context) {
             $faker = Faker\Factory::create();
             $context->getSession()->getPage()->findField('voucher_subject')->setValue($faker->text);
             $context->getSession()->getPage()->findField('voucher_nameRecipient')->setValue($faker->name);
             return true;
         }
     }
}

它将尝试在5秒内找到该元素,然后如果没有找到它则超时。它对Selenium2和Goutte很有用。


2
投票

从我的观点来看,现在可以做得更优雅:

$page = $this->getSession()->getPage();

$page->waitFor(5000,
    function () use ($page) {
        return $page->findField('voucher_subject')->isVisible();
    }
);

你也可以将它包装在一些private函数中。


0
投票

如果您使用的驱动程序仅模拟浏览器(如BrowserKit或Goutte),则只有在DOM正确组合并准备就绪时才能进行控制(当然,不能解释或执行任何js)。如果您使用Selenium2之类的东西,并且该字段是从异步调用构建的(如果我理解正确,这是您的情况),由您决定是否完整地加载页面。那是因为请求有一个响应,控件被传递回Behat进程。 这个问题的一个可能的解决方案是在每个ajax / async调用之前将一个类附加到正文,并在每次调用完成后立即将其删除。然后,在您的behat上下文中创建一个“spinner”函数,以检查要离开的类。

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