That's not terrible, but it could be better. We can install @testing-library/jest-dom
, which will add in some additional matchers for us to take advantage of.
npm install -D @testing-library/jest-dom
@testing-libary/jest-dom
will add the following matchers to expect
:
toBeDisabled
toBeEnabled
toBeEmptyDOMElement
toBeInTheDocument
toBeInvalid
toBeRequired
toBeValid
toBeVisible
toContainElement
toContainHTML
toHaveAccessibleDescription
toHaveAccessibleName
toHaveAttribute
toHaveClass
toHaveFocus
toHaveFormValues
toHaveStyle
toHaveTextContent
toHaveValue
toHaveDisplayValue
toBeChecked
toBePartiallyChecked
toHaveErrorMessage
Let's start simple by extending our matchers in this test file.
import { expect } from 'vitest';
import matchers from '@testing-library/jest-dom/matchers';
expect.extend(matchers);
Alternatively, if you're using the globally-available version of expect
, you can just import the library and it will automatically extend expect
.
import '@testing-library/jest-dom';
We can now update our test accordingly:
test('it should render the component', () => {
render(<Counter />);
const currentCount = screen.getByTestId('current-count');
expect(currentCount).toHaveTextContent('1');
});
Now, we'll get a significantly better error message. And we don't have to worry about the DOM API as much. Our new matcher will check the
Error: expect(element).toHaveTextContent()
Expected element to have text content:
1
Received:
0
Okay, that was all well and good, but let's get the test passing again.
test('it should render the component', () => {
render(<Counter />);
const currentCount = screen.getByTestId('current-count');
expect(currentCount).toHaveTextContent('0');
});
Additionally, .toHaveTextContent
will also accept a regular expression to make your texts more flexible.
Let's talk about how to set this up for our entire suite.