testing-library / cypress-testing-library

πŸ… Simple and complete custom Cypress commands and utilities that encourage good testing practices.
http://npm.im/@testing-library/cypress
MIT License
1.8k stars 152 forks source link

findBy* queries ignore subject provided by chained command if called inside of a `.within()` callback #201

Closed istateside closed 2 years ago

istateside commented 3 years ago

Relevant code or config

  <section>
    <button>Button Text 1</button>
    <div id="nested">
      <button>Button Text 2</button>
    </div>
  </section>
cy.get('section').within(() => {
  cy.get('#nested').findByText(/Button Text/).should('exist');
});

What you did: Ran a cypress-testing-library command with a chained subject inside of a within() callback.

I expected the findByText to be scoped to the current subject yielded by the last command in the chain.

What happened: The subject from the chained .get('#nested') is ignored - instead, the findByText is scoped to the subject yielded by the within() block above it.

TestingLibraryElementError
Timed out retrying after 4000ms: Found multiple elements with the text: /Button Text/

image

Problem description: This is happening because the getContainer util used in this library gives priority to the element provided by cy.state('withinSubject'), regardless of whether there is an explicit subject provided to the command.

Suggested solution: We should only scope to the withinSubject if cy.state('subject') returns undefined.

I have a PR up adding a new test for this functionality, and fixing the util with my suggestion.

IanVS commented 2 years ago

I think this can be closed by #201?

istateside commented 2 years ago

I think this can be closed by #201?

Yeah this can be closed, forgot to come back to this issue πŸ‘