Member-only story
The Most Important Assertions in Jest, React Testing Library Tests
Prioritize these assertions when writing component tests
Knowing what to expect()
in tests is not an easy problem. Having written hundreds of jest
, react-testing-library
tests, I believe I’ve gained enough experience to share useful advice.
In my previous blog post, What NOT To Assert in React Component Tests, I covered what one should not assert. I suggest reading it because this blog post will greatly overlap and you’ll notice that I refer to it multiple times.
Consequently, the goal of this blog post is to explain what you can assert and what I think you should assert when writing component tests
Note: code snippets are based on Jest and React Testing Library (RTL)
Two categories of assertions
Assertions can be categorized into two categories:
- UI assertions
- Non-UI assertions
Which assertions you should use usually depend on the test case. If a test is named updates button text
, then it‘s quite clear that you’ll want to have a UI assertion that asserts button text, e.g. expect(screen.getByText('Updated button')).toBeInTheDocument()