使用 Codeception 和 WebDriver 测试文本光标位置

Testing text cursor position using Codeception and WebDriver

使用 Codeception 和 Gherkin,我正在尝试弄清楚如何测试文本光标位置的自动更新:

When I click "New post"
Then the blinking text cursor should be in the "Title" field

代码是这样的:

<a href="#" id="js-move-text-cursor-to-post-title-input">
  New post
</a>

…

<label>
  Title
  <input type="text" name="title">
</label>

…

<!-- Some JavaScript to set the text cursor to the "Title" input field -->

所以,我的问题是,我可以在下面的步骤定义中写什么来测试这个功能?

/**
 * @Then the blinking text cursor should be in the :label field
 * @param string $label
 */
public function theBlinkingTextCursorShouldBeInTheField(string $label)
{
    // @TODO
}

tests/acceptance.suite.yml:

actor: AcceptanceTester
modules:
    enabled:
        - Symfony:
            part: SERVICES
        - Doctrine2:
            depends: Symfony
        - WebDriver:
            url: http://localhost:8000
            browser: chrome
        - \Helper\Acceptance

您应该测试按下的键是否出现在预期的字段中,而不是检查光标:

When I click "New post"
When I type "abcd"
Then the "Title" field has the value "abcd"

codeception 目前的 API 似乎没有提供获取活动元素或在活动字段中键入的方法。

所以你可能不得不使用底层 API.

$webdriver->switchTo()->activeElement() :

// click "New post"
$I->click('#js-move-text-cursor-to-post-title-input');

// type "abcd" in the focused field
$I->executeInSelenium(function($webdriver) {
  $webdriver->switchTo()->activeElement()->sendKeys('abcd');
});

// assert that the value "abcd" is in the expected field
$I->seeInField('input[name="title"]', 'abcd');

,或者用 executeJS :

// click "New post"
$I->click('#js-move-text-cursor-to-post-title-input');

// type "abcd" in the focused field
$I->executeJS('return document.activeElement')->sendKeys('abcd');

// assert that the value "abcd" is in the expected field
$I->seeInField('input[name="title"]', 'abcd');

,或使用底层键盘接口:

// click "New post"
$I->click('#js-move-text-cursor-to-post-title-input');

// type "abcd" in the focused field
$I->executeInSelenium(function($webdriver) {
  $webdriver->getKeyboard()->sendKeys('abcd');
});

// assert that the value "abcd" is in the expected field
$I->seeInField('input[name="title"]', 'abcd');

这似乎与提出的另一个问题非常相似:

也许这个问题的答案会对你有所帮助。