I'm new in TDD for the React. I've decided to use the react-testing-library to start TDD for development. Suppose that, I should check a prop and simple text in component:
import { render, screen } from '@testing-library/react';
import Card from '../Card';
test('render without crash', () => {
render(<Card />);
expect(screen.getByText('Card Component')).toBeInTheDocument();
});
test('title', () => {
render(<Card title="test" />);
expect(screen.getByText('test')).toBeInTheDocument();
});
I used render two times two check different types of rendering for my component. But I was worry about performance... Is it best practice to separately use render in any tests? or I should create something like this common variable:
const Component = render(<Card title={...} prop2={} prop3={} ... />);
then use Component instead using render again?
I don't this this would be a bad practice. I usually use one of these approach :
test(), if I always need the same setup for each test (props, contexts, redux store...),test(), so I can adjust props and context and test multiple configuration.See https://stackoverflow.com/a/61838982/2295549 for a more complete explanation, and some pros/cons.
But using render multiple times is not a bad practice, in fact it is a pattern used in official docs.