Test multiple react-select components on same page using Cypress

I am trying to test react-select components (v5) on a page using cypress. I can do this using the css classname when there is only one react select component on a page, but when there are multiple ones I'm having trouble adding a unique identifier to the component. I've tried adding a dataCy attribute to the select component but it doesn't show up in the DOM.

cy.get("[dataCy=reports-menu]").click()

<Select
            options={reportItems}
            isSearchable
            className="mb-4"
            placeholder="Water System Reports"
            onChange={handleMenuChange}
            defaultValue={{ label: "Inventory", value: "inventory" }}
            dataCy="reports-menu"
          />

I've also tried calling the component out by placeholder like this: cy.get(".css-319lph-ValueContainer").should("contain", "Inventory").click();

and then clicking on that item but I still get an error that

cy.click() can only be called on a single element. Your subject contained 2 elements. Pass { multiple: true } if you want to serially click each element

How can I specificity which react-select component on a page I want to click on when a page may contain multiple react-select components?

Upvotes: 1

Views: 1969

Answers (2)

Fody
Fody

Reputation: 32034

You can add aria-label="reports-menu" to the react-select. This attribute adds to the inner <input> element, which may or may not be the element you want to click.

The Cypress selector is

cy.get("[aria-label=reports-menu]")

You can also add id="reports-menu", which gets added to the top-most div of the Select elements, most likely this is your click target.

The Cypress selector is

cy.get("#reports-menu")

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18626

With contains you can use a combination of selector and text.

cy.contains('[placeholder="Water System Reports"]','Inventory').click()

Upvotes: 0

Related Questions