Cypress: what is the difference between `cy.contains` and `cy. findByText`

4.7k views Asked by At

findByText is from Cypress Testing Library https://testing-library.com/docs/cypress-testing-library/intro

and contains comes with Cypress "natively"

I wonder what is the difference between them and when I should use one over the other?

1

There are 1 answers

2
pavelsaman On

I think one difference could be found here: https://github.com/testing-library/cypress-testing-library#differences-from-dom-testing-library

find* commands will fail if more than one element is found that matches the criteria which is not how built-in Cypress commands work, but is provided for closer compatibility to other Testing Libraries.

That's not how contains() works. From the docs: https://docs.cypress.io/api/commands/contains.html#Single-Element

Only the first matched element will be returned

contains() also works with preferences, e.g. contains() yields <button> element even if it's higher in the tree when the deeper element is e.g. <span>. So it prefers <button> elements over deeper elements if you don't pass a selector argument the command. There're other examples in the docs for this command.


So it seems to me now that find* commands in the Cypress Testing Library more closely resemble the behaviour of other testing libraries as it's said in the docs. With contains(), you perhaps need more knowledge about how it works so you get elements you want and not some other ones because e.g. you don't understand how this preference logic works.