Search code examples
reactjscypress

Cypress - can't click on span


In my React.js code I have the following:

        <span 
            onClick={addToList} 
            className='ms-2 pt-2' 
            title='Adding a new row.'
            data-testid='t-editableListItem-add'>
            <BsFilePlus size={25} role='button' />
        </span>

In unit test the span can be clicked on:

await userEvent.click(screen.getByTestId('t-editableListItem-add'));

However in Cypress (13.6.4) I can't do the same:

    cy.findByTestId('t-editableListItem-add').click();

or

    cy.findByTestId('t-editableListItem-add').findByRole('button').click();

neither of them works.

I've even tried the realClick() from https://github.com/dmtrKovalenko/cypress-real-events but it didn't help.

Any idea please what I am doing wrong?


Solution

  • If userEvent.click(...) is working for you in unit tests, you can also import it into Cypress tests and use it there.

    You just need to provide it with the DOM element, which can be obtained from the Cypress query via the yielded jQuery object.

    import userEvent from '@testing-library/user-event'
    // also requires install of @testing-library/dom
    
    it('clicks a button using userEvent', () => {
    
      cy.get('[data-testid="t-editableListItem-add"]')
        .then($span => {
          const element = $span[0]
          userEvent.click(element)
        })
    })
    

    Missing event listener

    If that does not work, the problem could be that the event handler is not attached at the time your Cypress test attempts to click.

    See When Can The Test Click for a full rundown of this problem.

    The test can wait for the event listener using the hasEventListeners command that comes with the cypress-cdp package.

    it('clicks a button using userEvent', () => {
    
      // wait for the event listener to be attached
      cy.hasEventListeners('[data-testid="t-editableListItem-add"]', { type: 'click' })
    
      cy.get('[data-testid="t-editableListItem-add"]').click()
    })