dman
dman

Reputation: 11064

What is the best way to grab this input element? Can not use attr values

I have a app the creates forms dynamically. In the e2e tests, the e2e creates the form and after the test form will be deleted from the db.

This means I can not use class, ids, or data attribute values because their values are dynamically generated. ie: <div id="input_1642" class="input_1642">. Being the form is created by e2e and destroyed after the test is done, there is no way for me to know their values and they will not persist.

For the following html, in which the only unique value I really have is the required input in <span style="white-space: pre-wrap; overflow-wrap: break-word;">required input</span>

Using Playwright, and not being able to use class, id, or data attribute values, what is the cleanest way to grab (selector) the input so I can page.fill()? I was hoping to avoid having using Xpath

<div id="input_1642" class="input_1642">
  <div>
    <div>
      <div class="ant-row ant-form-item" style="row-gap: 0px;">
        <div class="ant-col ant-form-item-label ant-form-item-label-left">
          <label for="input_1642" class="ant-form-item-required" title="">
            <span>
              <span style="white-space: pre-wrap; overflow-wrap: break-word;">required input</span>
            </span>
          </label>
        </div>
        <div class="ant-col ant-form-item-control">
          <div class="ant-form-item-control-input">
            <div class="ant-form-item-control-input-content">
              <span>
                <span>
                  <input formbuilderhiddenfrom="" data-cy="form_item_input_1642_3" data-navigate="false" id="input_1642" class="ant-input align-input-items" type="text" value="">
                  <span></span>

Upvotes: 1

Views: 252

Answers (2)

Alapan Das
Alapan Das

Reputation: 18624

How about you use a partial selector like this:

page.fill('[data-cy*="form_item_input_"]', 'some text')

To pinpoint the correct element, you can further use the Nth Selector

page.fill('[data-cy*="form_item_input_"] >> nth=0', 'some text')

Upvotes: 1

hardkoded
hardkoded

Reputation: 21695

According to the docs, you can find the element by the text of its label.

You have a label for that input. So you could try something like:

await page.locator('text=required input').fill('some text');

Upvotes: 1

Related Questions