What is shallow rendering in React testing?
Shallow rendering is a technique used in React testing where a component is rendered only one level deep.
It renders the component without rendering its child components.
When and why use shallow rendering:
- To test a component in isolation without worrying about the behavior of its children.
- To focus on the component's internal logic, props, and state changes.
- Useful for unit tests where you want to test one specific component alone.
Example with Enzyme:
import { shallow } from 'enzyme'; import MyComponent from './MyComponent'; test('renders title', () => { const wrapper = shallow(<MyComponent />); expect(wrapper.find('h1').text()).toBe('Hello World'); });
Important note:
Today, shallow rendering is used less frequently because libraries like React Testing Library promote testing based on user interactions, not component internals.