Search code examples
e2e-testingplaywright

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>

Solution

  • 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')