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
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
Share Improve this question edited Nov 22, 2019 at 14:35 olena_k91 asked Nov 22, 2019 at 14:09 olena_k91olena_k91 1011 gold badge1 silver badge4 bronze badges 5 |2 Answers
Reset to default 12https://testing-library.com/docs/dom-testing-library/api-queries
getBy
will throw errors if it can't find the elementfindBy
will return and reject a Promise if it doesn't find an elementqueryBy
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
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
cy.findByTestId(...)
with.should("not.exist")
– user9161752 Commented Nov 22, 2019 at 19:18findBy
andgetBy
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 doescy.get('[data-testid="my-button"]')
return when element is not in a DOM? – olena_k91 Commented Nov 25, 2019 at 11:44