From DOM Testing-library Docs – Appearance and Disappearance
Asserting elements are not present
The standard
getBymethods throw an error when they can’t find an element, so
if you want to make an assertion that an element is not present in the DOM,
you can usequeryByAPIs instead:const submitButton = screen.queryByText('submit') expect(submitButton).toBeNull() // it doesn't existThe
queryAllAPIs version return an array of matching nodes. The length of the
array can be useful for assertions after elements are added or removed from the
DOM.const submitButtons = screen.queryAllByText('submit') expect(submitButtons).toHaveLength(2) // expect 2 elements
not.toBeInTheDocumentThe
jest-domutility library provides the
.toBeInTheDocument()matcher, which can be used to assert that an element is
in the body of the document, or not. This can be more meaningful than asserting
a query result isnull.import '@testing-library/jest-dom/extend-expect' // use `queryBy` to avoid throwing an error with `getBy` const submitButton = screen.queryByText('submit') expect(submitButton).not.toBeInTheDocument()