DEV Community

Tim Winfred (They/He)
Tim Winfred (They/He)

Posted on

Using Jest to check that a React Component doesn't render

I was working on writing some Jest tests at work recently and ran into an issue with getting a false-positive when testing casing in which a component shouldn't be rendered.

The issue happened because I was using the React testing library's queryByText query. My expectation was that the test would fail if that test didn't exist, but that wasn't the case.

After playing around with the tests by throwing in some queryByText arguments that should have caused the test to fail, I was surprised to see the test still passing.

Here's what I had (modified for public consumption):

test("does not render component if user is not logged in", async (done) => {
    // All other logic has been stripped from this test sample
    const { queryByText } = render(<AccountDashboard />);

    await waitFor(() => {
        expect(queryByText("Welcome to your dashboard!")).toBeNull();
        done();
    });
});
Enter fullscreen mode Exit fullscreen mode

According to the React documentation, the queryBy... method:

Returns the matching node for a query, and return null if no elements match. This is useful for asserting an element that is not present.

Unfortunately, the expect methods weren't failing the the tests were passing regardless of what the text was that I passed into queryByText. Feeling slightly frustrated, I set out to find a way to test for an empty component and settled on the following solution:

test("does not render component if user is not logged in", async (done) => {
    // All other logic has been stripped from this test sample
    const { contaner } = render(<AccountDashboard />);

    await waitFor(() => {
        expect(container.childElementCount).toEqual(0);
        done();
    });
});
Enter fullscreen mode Exit fullscreen mode

Have you been able to find a better solution to testing cases when you expect that a component will NOT render? Please let me know in the comment section!

Happy testing =)

Top comments (4)

Collapse
 
ucorina profile image
Corina Udrescu • Edited

You can now also use toBeEmptyDOMElement:

const { container } = render(<SomeComponent />);
expect(container).toBeEmptyDOMElement();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tpaksu profile image
Taha Paksu • Edited

I've found that expect( container.baseElement.innerHTML ).toEqual( '<div></div>' ); also works.

Collapse
 
pke profile image
Philipp Kursawe • Edited

Just use expect(render(...).toJSON()).toBeNull(). Its faster than waiting for elements to not appear.

p.s. your example has a typo: it destructures contaner instead of container

Collapse
 
jimjja profile image
Jemal Ahmedov

If you are using test IDs, you can also use queryByTestId() which will return falsy value when element is not found. Happy testing!