DEV Community

Jen C.
Jen C.

Posted on

Jest - How to verify that an element does not exist in the rendered output

Resources

Types of Queries

.not

not.toBeInTheDocument

.toBeNull()

waitForElementToBeRemoved

ByTestId

.toThrow(error?)

waitFor

Document: querySelector() method

.not.toBeInTheDocument()

For example, according to the Types of Queries documentation,queryBy... returns null if no matching elements are found. Therefore, we can use .not.toBeInTheDocument() to assert that the element with the test ID user-profile-icon is not rendered in the DOM.

it('does not render the icon element when the "icon" prop is missing', () => {
  expect(screen.queryByTestId('user-profile-icon')).not.toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

toBeNull()

The above example can be rewritten as follows:

it('does not render the icon element when the "icon" prop is missing', () => {
  expect(screen.queryByTestId('user-profile-icon')).toBeNull();
});
Enter fullscreen mode Exit fullscreen mode

When a query method throws an error if no elements are found

Query methods getBy..., getAllBy..., findBy..., and findAllBy... will throw an error when they cannot find elements. So we can use .toThrow() to verify that certain elements are not rendered.

For example, to verify that an element with the text 'Not Present' does not exist in the render output:

beforeEach(() => {
  render(<MyComponent />);
});

...

it('query methods throw when elements are not found', () => {
  expect(() => screen.getByText('Not Present')).toThrow();
});
Enter fullscreen mode Exit fullscreen mode

In some cases, we may want to verify that an assertion fails when an element is not in the DOM. This can be done using .toThrow(), though it's less common and typically not recommended for general absence checks.

For example, we can use querySelector() to select an element by its CSS class and assert that calling .toBeInTheDocument() on a non-existent element (i.e., null) throws an error. For example:

describe('<Nav /> of <Header />', () => {
  let renderResult = null;

  beforeEach(() => {
    renderResult = render(<Nav {...props} />);
  });

  it('should hide sub menu', async () => {
    expect(() =>
      expect(
        renderResult.container.querySelector('.main-header-sub-menu')
      ).toBeInTheDocument()
    ).toThrow();
  });
});
Enter fullscreen mode Exit fullscreen mode

When the Testing Library may not update the DOM immediately

  • Asynchronous State Updates
  • Debounced or Throttled Updates
  • State Updates After Re-render
  • Transitions and Animations
  • External Event Triggers
  • ...

See Async Methods

Top comments (0)