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?
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.
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.
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.
You can use jest-dom's toBeEmpty
:
const { container } = render(<MyComp ItemLength={1} />) expect(container.firstChild).toBeEmpty()
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With