【问题标题】:How to handle Race Conditions in Behat/Mink如何在 Behat/Mink 中处理比赛条件
【发布时间】:2021-02-26 01:12:07
【问题描述】:

所以我在 Behat/Mink 中进行了以下非常简单的测试。按下按钮时,会显示一个元素,然后我会用一些文本填充该元素。有时此测试有效,有时则无效。这是基本结构:

file.blade.php

<button id="show-inputs">Show</button>
<div id="inputs" class="hidden">
  <span>Input</span>
  <input type="text" id="test-input"/>
</div>

script.js

jQuery(function($){
  $('#show-inputs').on('click', function() {
    $('#inputs').removeClass('hidden');
  });
});

TestingFeature.feature

@javascript
Scenario: Testing Input Show/Fill
  Given I am on "/"
  Then I press "show-inputs"
  And I wait for javascript to finish loading
  Then I fill in "test-input" with "This is a Test"
  ...

FeatureContext.php

public function iWaitForJavascriptToFinishLoading() {
  $this->getSession()->wait(10000, '$.active === 0');
}

如您所见,这是一个简单的测试;导航到/后,触发#show-inputs的点击,等待JS完成(即给时间显示#inputs div),然后用简单的测试填入#test-input

运行这些测试,有时会奏效,有时则不会。这是behat的输出:

...
Then I press "show-inputs"                        # FeatureContext::pressButton()
And I wait for javascript to finish loading       # FeatureContext::iWaitForJavascriptToFinishLoading()
Then I fill in "test-input" with "This is a Test" # FeatureContext::fillField()
  Element is not visible and can not be focused

错误Element is not visible and can not be focused 有时只出现,表明显示元素> 填充元素的竞争条件,以不正确的顺序发生。我认为And I wait for javascript to finish loading,它等到$.active0 会处理这个问题,但显然它没有。我想知道这是否与使用类 hidden (display:none) 与简单的 $('{$selector}').show() 有关,但我不确定。

我可以按照And I wait for "inputs" to be "visible" 的方式添加一个新的检查,它会等到$('{$selector}').is(':visible') === true,但这感觉不对。

以前有人遇到过这个问题吗?

【问题讨论】:

    标签: javascript php race-condition behat mink


    【解决方案1】:

    我最终采用了我认为必须的方式,使用And I wait for "test-input" to be "visible",并在FeatureContext.php 中使用自定义定义:

    /**
     * @Then I wait for :elementId to be :visibility
     */
    public function iWaitForElementToBe($elementId, $visibility) {
      if ($visibility != 'visible' && $visibility != 'hidden') {
        throw new Exception("Invalid visibility pseudo `{$visibility}` supplied: Must be one of `visible`, `hidden`");
      }
      $this->getSession()->wait(1000, "\$('#{$elementId}').is(':{$visibility}') === true");
    }
    

    然后在TestingFeature.feature:

    @javascript
    Scenario: Testing Input Show/Fill
      Given I am on "/"
      Then I press "show-inputs"
      And I wait for "test-input" to be "visible"
      Then I fill in "test-input" with "This is a Test"
    

    唯一需要注意的是,如果同时显示多个元素,则需要为每个元素重复 And I wait for ... to be ...,即使它们在同一行代码中切换为可见/隐藏(例如 $('#id, #id2').removeClass('hidden') )。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多