The code `import '@testing-library/jest-dom/extend-expect';` enhances Jest, a JavaScript testing framework,...
The code import '@testing-library/jest-dom/extend-expect';
enhances Jest, a JavaScript testing framework, with additional matchers provided by the @testing-library/jest-dom
library.
Here's what it does:
-
Adds Custom Matchers: Jest by default provides some basic testing matchers. When you import
@testing-library/jest-dom/extend-expect
, it extends those matchers, allowing you to write more expressive tests specifically tailored for testing DOM elements. -
Examples of Matchers Added:
toBeInTheDocument()
: Asserts whether an element is part of the DOM.toHaveAttribute()
: Asserts whether an element has a specific attribute.toHaveClass()
: Asserts whether an element has a particular class.toHaveStyle()
: Asserts whether an element has specific inline styles.toBeVisible()
: Asserts whether an element is visible in the document.toHaveTextContent()
: Asserts whether an element has the expected text content.
-
Why It's Useful: These matchers make it easier to test the state and appearance of elements in a clear and human-readable way, compared to manually writing custom assertions.
Example:
import '@testing-library/jest-dom/extend-expect';
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';
test('displays the correct heading', () => {
const { getByText } = render(<MyComponent />);
const heading = getByText('Hello, World!');
expect(heading).toBeInTheDocument();
expect(heading).toHaveTextContent('Hello, World!');
expect(heading).toHaveClass('main-heading');
});
Without @testing-library/jest-dom
, you would need to write much more boilerplate to achieve the same assertions, thus making this import very convenient for testing React and DOM-based applications.