Re-rendering a component is an important part of testing, especially when you are testing stateful components. Jest, React Testing Library and Enzyme provide methods to re-render components with updated props or state.
1- Re-rendering a Component in Jest and Enzyme
In Jest and Enzyme, you can re-render a component by updating its state or props. To do this, you can use the setState()
method to update the state, or the setProps()
method from Enzyme to change the props.
Here’s an example of how to re-render a component by updating its state using the setState()
method:
import React, { Component } from 'react';
import { shallow } from 'enzyme';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
// Testing
describe('MyComponent', () => {
it('should re-render component when state is updated', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('p').text()).toBe('0');
wrapper.setState({ count: 1 });
expect(wrapper.find('p').text()).toBe('1');
});
});
In this example, we are using the shallow
method from Enzyme to render the component. Then we are using setState()
to update the count
state, which triggers a re-render of the component. Finally, we are using expect
statements to check that the component has re-rendered correctly.
2- Re-rendering a Component in React Testing Library
In React Testing Library and Jest, you can re-render a component by updating its state or props using the rerender()
method. The rerender()
method allows you to re-render a component with updated props or state without unmounting and remounting it.
Here’s an example of how to re-render a component in React Testing Library by updating its state using the rerender()
method:
import React, { useState } from 'react';
import { render, screen } from '@testing-library/react';
function MyComponent(props) {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<p>{count}</p>
<button onClick={handleClick}>Increment</button>
<p>{props.text}</p>
</div>
);
}
describe('MyComponent', () => {
it('should re-render component when state is updated', () => {
const { rerender } = render(<MyComponent text="Hello" />);
expect(screen.getByText('0')).toBeInTheDocument();
// update state and re-render
rerender(<MyComponent text="Hello" />);
expect(screen.getByText('1')).toBeInTheDocument();
});
});
In this example, we are using the render
method from React Testing Library to render the component. Then we are using the rerender
method to re-render the component by passing updated props or state. Finally, we are using the screen
object from React Testing Library to query the rendered component and check if it has re-rendered correctly.
Photo from unsplash