behat fillField xpath 给出错误?

behat fillField xpath giving error?

这行代码:

$this->fillField('xpath','//fieldset[@id="address-container"]/input[@name="address_add[0][city]"]', "Toronto");

给我这个错误

Form field with id|name|label|value|placeholder "xpath" not found. (Behat\Mink\Exception\ElementNotFoundException)

我想在我的 fillField 中使用 xpath 的原因是因为我的 html 文档中实际上有多个 input[@name="address_add[0][city]"]。我认为 xpath 可以让我专门针对要填充的字段。

仅填写 fieldset[@id="address-container"] 的后代 input[@name="address_add[0][city]"] 的最佳方法是什么?

您没有正确使用该方法。

正如我在此处看到的那样,xpath 被用作选择器。 该方法需要 2 个参数:
identifier - 属性之一的值 'id|name|label|value'
value - 您需要设置为值的字符串

如果你想使用css|xpath那么你需要先使用find方法。

例如:

$this->find('xpath', 'your_selector')->setValue('your_string');

Please note that find might return null and using setValue will result in a fatal exception.

你应该有这样的东西:

$field = find('xpath', 'your_selector');

if ($field === null) {
    // throw exception
}

$field->setValue('your_string');

您的选择器也可以写成:

#address-container input[name*=city] - this with css

//fieldset[@id="address-container"]//input[contains(@name, 'city')]  - this with xpath

Make sure you take advantage of your IDE editor when you have any doubts using a method and you should find a php doc with what parameters are expected and what the method will return.

If you are using css/xpath a lot you could override find method to detect automatically the type of selector and to use it like $this->find($selector);

Also you could define another method to wait for the element and to handle the exception in one place, for example waitForElement($selector) that could contain a conditional wait up to 10 seconds and that throws exception if not found.