Как открыть отключенные поля в Selenium - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь заполнить форму с помощью Selenium, но в форме есть отключенное поле.

Отключенное поле

Disabled field

The field is only editable when I modify the field above it.

Open field

Open field

When I set the value directly using the code below, the field is not open for editing

js.executeScript("document.getElementById('field_id').value='" + brand + "'");

Example

Example of not editable field

I tried to simulate the click in the field, press the tab key, press the enter key, but none had any effect.

Is there any way for me to trigger the same event that the user is performing on the screen to release the field through selenium or javascript?

In the HTML code, the options are not listed, so the options are loaded from a javascript function that is executed after filling the first field

Options

Параметры

Ответы [ 2 ]

1 голос
/ 13 июля 2020

Поскольку мне это очень понравилось, я скопирую вступление к Tschallackas:

Ваш тест ошибочен. Вы не следите за поведением пользователя.

К сожалению, я полностью не согласен с остальной частью ответа: (

Я хотел бы спросить ПОЧЕМУ вы пытаетесь использовать JavaScript? Сделал бы это настоящий Пользователь? Я действительно в этом сомневаюсь!

Важнейшая вещь с End2End-Tests - как можно точнее моделировать ваше поведение пользователя. Поэтому я предлагаю использовать Webdriver для подобных действий в вашем Seleniumtest.

Select dropdown = new Select(webdriver.findElement(By.id("field_id")));
dropdown.selectByVisibleText("ONESOURCE");

(при условии, что вы используете Java по тегу в вашем вопросе)

0 голосов
/ 13 июля 2020

Ваш тест ошибочен. Вы не следуете за поведением пользователя.

Вы делаете:

js.executeScript("document.getElementById('field_id').value='" + brand + "'");

Которая пытается изменить значение в раскрывающемся списке. Это не работает, потому что раскрывающиеся списки работают через selectedIndex, который можно использовать для получения правильного значения из коллекции параметров в раскрывающемся элементе. Кроме того, когда пользователь изменяет значение, запускается событие изменения, которое уведомляет другие сценарии, прослушивающие это событие, о том, что что-то изменилось. Вам также необходимо эмулировать это, чтобы запустить ваш сценарий изменения.

js.executeScript("let select = document.getElementById('field_id');"+
                 "select.selectedIndex = 1;/* change this to the value corresponding to the correct index of the value you wish to test. */"+
                 "select.dispatchEvent(new Event('change'));");

См. Пример ниже, чтобы узнать, как javascript должен работать.

document.getElementById('field_id').addEventListener('change', (e) => {
   if(e.target.options[e.target.selectedIndex].value > 1) {
      document.getElementById('the_disabled').disabled = false;
   }
   else {
      document.getElementById('the_disabled').disabled = true;
   }
});
document.getElementById('trigger').addEventListener('click',() => {
   let select = document.getElementById('field_id');
   select.selectedIndex = 1;// change this to the value corresponding to the correct index of the value you wish to test.
   select.dispatchEvent(new Event('change'));
});
<select id="field_id">
 <option value="1">--none--</option>
 <option value="2">COMPANY A</option>
 <option value="3">COMPANY B</option>
</select>
<BR/>
<select id="the_disabled" disabled="disabled">
 <option value="0">--none--</option>
 <option value="1">SELECT A</option>
 <option value="2">Select B</option>
</select>
<BR/>
<button id="trigger">Trigger selenium emulation</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...