Skip to content

Latest commit

 

History

History
85 lines (66 loc) · 3.55 KB

Extending Matchers for Testing Library.md

File metadata and controls

85 lines (66 loc) · 3.55 KB

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

Additional Matchers

@testing-libary/jest-dom will add the following matchers to expect:

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

Making the Test Pass Again

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.