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();
    });
});

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();
    });
});

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 =)

12