How to test if element exists/doesn't exist with Jest and react-testing-library
Tim Kamanin 🚀
Posted on December 31, 2019
At first, let's create a simple avatar component:
function Avatar({ username, src, usernameIsHidden = false }) {
return (
<div>
<img src={src} />
{!usernameIsHidden && <h4 data-testid="username">{username}</h4>}
</div>
);
}
The usernameIsHidden
flag allows us to toggle visibility of a username.
We'll test username
element for existence and non-existence.
1. Here's how to test if the element exists and its content matches our expectation:
import { render } from "@testing-library/react";
test("username exists", () => {
const { getByTestId } = render(
<Avatar username="Timonweb" src="https://example.com/avatar.jpg" />
);
expect(getByTestId(/username/i).textContent).toBe("Timonweb");
});
2. We can also test if the element exists at all:
import { render } from "@testing-library/react";
test("username exists", () => {
const { queryByTestId } = render(
<Avatar username="Timonweb" src="https://example.com/avatar.jpg" />
);
expect(queryByTestId(/username/i)).toBeTruthy();
});
3. Finally, this is how to test for the non-existence of the element:
import { render } from "@testing-library/react";
test("username doesn't exist", () => {
const { queryByTestId } = render(
<Avatar
username="Timonweb"
src="https://example.com/avatar.jpg"
usernameIsHidden
/>
);
expect(queryByTestId(/username/i)).toBeNull();
});
In cases 2 and 3, we use queryByTestId
instead of getByTestId
. queryByTestId
doesn't fail when the queried element doesn't exist, instead, it returns either a value or null
and that's what we test with expect().toBeTruthy()
and expect().toBeNull()
.
💖 💪 🙅 🚩
Tim Kamanin 🚀
Posted on December 31, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How to test if element exists/doesn't exist with Jest and react-testing-library
December 31, 2019