7

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

olena_k91
  • 81
  • 1
  • 1
  • 4
  • 1
    Some of those aren't part of the Cypress API - are you also using e.g. https://testing-library.com/docs/cypress-testing-library/intro? – jonrsharpe Nov 22 '19 at 14:17
  • Yes, I am using "testing-library/cypress" – olena_k91 Nov 22 '19 at 14:34
  • Might be worth raising an issue with the maintainers if they behave differently from the built-in methods. – jonrsharpe Nov 22 '19 at 14:52
  • See this [comment](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/testing-library__cypress/index.d.ts#L34), 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")` –  Nov 22 '19 at 19:18
  • Thanks, I found the same information in here https://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? – olena_k91 Nov 25 '19 at 11:44

2 Answers2

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

sunwukung
  • 2,815
  • 3
  • 41
  • 56
0

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

ChrisE
  • 376
  • 4
  • 14