Cypress getByTestId, queryByTestId, findByTestId to check if element doesn't exist
Asked Answered
B

2

9

I am trying to check if element doesn't exist in a DOM Tree with Cypress and testing-library/cypress.

If I try to do cy.getByTestId("my-button").should("not.exist") test fails because it couldn't find element.

If I do cy.findByTestId("my-button").should("not.exist") it also fails because of time out.

The test does work if I do either cy.queryByTestId("my-button").should("not.exist") or

cy.get('[data-testid="my-button"]').should("not.exist").

Can someone please explain what's the difference between all 4.

Thanks

Burck answered 22/11, 2019 at 14:9 Comment(5)
Some of those aren't part of the Cypress API - are you also using e.g. testing-library.com/docs/cypress-testing-library/intro?Tormoria
Yes, I am using "testing-library/cypress"Burck
Might be worth raising an issue with the maintainers if they behave differently from the built-in methods.Tormoria
See this comment, says findBy*` APIs search for an element and throw an error if nothing found, so logically you cannot use cy.findByTestId(...) with .should("not.exist")Shearin
Thanks, I found the same information in here testing-library.com/docs/react-testing-library/cheatsheet, saying that findBy and getBy return error if element isn't found that's why cannot be used for my test. queryBy returns null and doesn't fail the test. But what does cy.get('[data-testid="my-button"]') return when element is not in a DOM?Burck
C
12

https://testing-library.com/docs/dom-testing-library/api-queries

  • getBy will throw errors if it can't find the element
  • findBy will return and reject a Promise if it doesn't find an element
  • queryBy will return null if no element is found:

This is useful for asserting an element that is not present.

looks like queryBy is your best choice for this problem

Chivalrous answered 12/6, 2020 at 14:23 Comment(0)
S
3

In the latest version of Cypress Testing Library they have removed queryBy.

Cypress Testing Library | Intro

If you want to check if something doesn't exist just use findBy, but put a should() straight afterwards. It won't time out in that case.

cy.findByText('My error message').should('not.exist')

Discussion on GitHub

Sonny answered 7/9, 2022 at 13:2 Comment(1)
As of end of 2023 this should be the accepted answerLitman

© 2022 - 2024 — McMap. All rights reserved.