Home > Back-end >  How to test react components on a site in Cypress E2E?
How to test react components on a site in Cypress E2E?

Time:11-11

I have a project in which some components, such as dropdowns, are written in React. enter image description here In this case, I can't select an item from the dropdown because the DOM doesn't show what's in that dropdown.

<div ><div ><div  id="react-select-6-placeholder">Select...</div><input id="react-select-6-input" tabindex="0" inputmode="none" aria-autocomplete="list" aria-expanded="false" aria-haspopup="true" role="combobox" aria-readonly="true" aria-describedby="react-select-6-placeholder"  value=""></div><div ><div  aria-hidden="true"><span></span></div></div></div>

How to conduct E2E tests in this case? Can someone explain or share their experience? I did not find information on the Internet. thank you

I looked for this component in the source code, but there are no files with react in the project code, these components are in node_modules, and it is not clear how to access this dropdown

CodePudding user response:

This looks like the react-select control (judging by the classes).

This "hair-trigger" behavior makes it hard to find the options, the list disappears upon any mouse action.

The way I do it is

  • open the devtools

  • right-click the select, click inspect to find it in devtools

  • click the select on the page to open it, repeat a few times to open and close, watch the devtools

  • an element in devtools appears and disappears when menu is opened and closed. The element has format like this: <div id="react-select-6-listbox">, but the number in the id varies depending on how many selects are used on the page.

We now know the id of the options wrapper, so this is the test code:

cy.get('.Select__control')    
  .parent()                                    // the top-level of react-select
  .click()                                     // open the list

cy.get('[id^="react-select"][id$="listbox"]')  // the injected options wrapper
  .within(() => {
    cy.contains('5 - May').click()             // select an option        
  })

cy.get('.Select__control')   
  .find('.Select__placeholder')
  .should('contain', '5 - May')                // verify selected text

If the 5 - May text is unique on the page you can just select it after opening the dropdown, but using .within() on the wrapper is safer.

  • Related