Library/react [2021]: Testing

Here’s a concise write-up on , covering what it is, why it’s used, and a practical example. Testing Library / React: Write-Up What Is It? Testing Library is a family of testing utilities that encourage testing React components the way a user would interact with them. The specific package @testing-library/react integrates with Jest and other test runners to query and interact with the DOM. Core philosophy: “The more your tests resemble the way your software is used, the more confidence they can give you.” Why Use It Over Alternatives (like Enzyme)? | Feature | Testing Library | Enzyme | |---------|----------------|--------| | Query by role/text/label | ✅ First-class | ⚠️ Possible but not encouraged | | Access to component internals (state, props) | ❌ Explicitly avoided | ✅ Easy | | Tests simulate real user behavior | ✅ High | ⚠️ Lower | | Maintenance with refactoring | Low | High (if testing internals) |

import render, screen from '@testing-library/react'; import Greeting from './Greeting'; test('displays the correct greeting', () => render(<Greeting name="Alice" />); const heading = screen.getByText(/hello, alice!/i); expect(heading).toBeInTheDocument(); ); Use userEvent (recommended over fireEvent for realistic behavior):

export default function Greeting( name ) return <h1>Hello, name!</h1>;

Here’s a concise write-up on , covering what it is, why it’s used, and a practical example. Testing Library / React: Write-Up What Is It? Testing Library is a family of testing utilities that encourage testing React components the way a user would interact with them. The specific package @testing-library/react integrates with Jest and other test runners to query and interact with the DOM. Core philosophy: “The more your tests resemble the way your software is used, the more confidence they can give you.” Why Use It Over Alternatives (like Enzyme)? | Feature | Testing Library | Enzyme | |---------|----------------|--------| | Query by role/text/label | ✅ First-class | ⚠️ Possible but not encouraged | | Access to component internals (state, props) | ❌ Explicitly avoided | ✅ Easy | | Tests simulate real user behavior | ✅ High | ⚠️ Lower | | Maintenance with refactoring | Low | High (if testing internals) |

import render, screen from '@testing-library/react'; import Greeting from './Greeting'; test('displays the correct greeting', () => render(<Greeting name="Alice" />); const heading = screen.getByText(/hello, alice!/i); expect(heading).toBeInTheDocument(); ); Use userEvent (recommended over fireEvent for realistic behavior):

export default function Greeting( name ) return <h1>Hello, name!</h1>;