Calum Page
Calum Page

Reputation: 63

Testcafe - how do I iterate over selectors of different element types?

I have a React address form which is config driven, and each element could either be a text <input> or a <select> dropdown. When trying to fill in the form using the code below, the text inputs are populated successfully, but the select element can't be found. If I remove the select elements from the loop and select them individually afterwards, it works fine. The MOCKS.deliveryAddress values are just strings.

  const addressFields = {
    addressLine2: Selector('[data-testid="input-addressLine2"]'),
    addressLine1: Selector('[data-testid="input-addressLine1"]'),
    addressLine3: Selector('[data-testid="input-addressLine3"]'),
    addressLine4: Selector('[data-testid="input-addressLine4"]'),
    postalCode: Selector('[data-testid="input-postalCode"]'),
  };

  const fieldConfig = {
    addressLine1: 'text',
    addressLine2: 'text',
    addressLine3: 'text',
    addressLine4: 'select',
    postalCode: 'text',
  };

  const enterAddress = async () => {
    await Promise.all(
      Object.keys(addressFields).map(async (field) => {
        if (fieldConfig[field] === 'text') {
          if (MOCKS.deliveryAddress[field]) {
            await t.typeText(
              addressFields[field],
              MOCKS.deliveryAddress[field],
              {
                replace: true,
              },
            );
          }
        } else {
          await t.click(addressFields[field]);
          await t.click(
            addressFields[field]
              .find('option')
              .withText(MOCKS.deliveryAddress[field]),
          );
        }
      }),
    );
  };
}

I get the error 1) The element that matches the specified selector is not visible.

Am I doing something wrong here in how I handle the selector inside a map?

Thanks in advance!

Upvotes: 2

Views: 760

Answers (2)

Calum Page
Calum Page

Reputation: 63

Turns out I was doing it wrong! I should have been chaining the click events for opening the dropdown and selecting an option, rather than awaiting the select click and then awaiting the option click. E.g.

await t
  .click(addressFields[field])
  .click(
    addressFields[field]
    .find('option')
    .withText(MOCKS.deliveryAddress.addressLine4),
  );

Upvotes: 2

mlosev
mlosev

Reputation: 5227

According to the TestCafe documentation, the element is considered as 'visible' if it does not have display: none or visibility: hidden CSS properties and has non-zero width and height. Using the browser development tool to investigate the properties of elements used in tests.

Upvotes: 2

Related Questions