Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React testing library - check the existence of empty div

I'm testing a component where if ItemLength = 1, render returns null.

const { container, debug } = render(<MyComp ItemLength={1} />);

When I call debug() in my test, it shows a <div />. How do I check that the component is returning an empty div in my test?

like image 935
blankface Avatar asked May 23 '19 02:05

blankface


People also ask

What does queryByTestId return?

queryByTestId<E extends Element> method. Returns a single element with the given testId value for the data-test-id attribute, defaulting to an exact match.

Where is the checkbox in react test library?

Solution: You can test the checkbox using react-testing-library, You just have to fireEvent. click the checkbox. In my code, there is a basic div with style display: none or display: block what is based on whether a checkbox is checked or not.

Do you need jest for react testing library?

React Testing Library is not specific to any testing framework; we can use it with any other testing library, although Jest is recommended and preferred by many developers. create-react-app uses both Jest and React Testing Library by default.


2 Answers

You can use jest-dom's toBeEmpty:

const { container } = render(<MyComp ItemLength={1} />) expect(container.firstChild).toBeEmpty() 
like image 195
Giorgio Polvara - Gpx Avatar answered Oct 03 '22 10:10

Giorgio Polvara - Gpx


The following should work as well without extending jest's expect:

const { container } = render(<MyComp ItemLength={1} />) expect(container.firstChild).toBeNull(); 

Update: the new way in 2020

import { screen } from '@testing-library/react';  ...  render(<MyComp ItemLength={1} />);  const child = screen.queryByTestId('data-testid-attribute-value');  expect(child).not.toBeInTheDocument(); 
like image 32
Karolis Grinkevičius Avatar answered Oct 03 '22 11:10

Karolis Grinkevičius