Reputation: 245
I want to test a component and it contains conditional rendering. So if a state is true, the JSX-HTML should render, if false not.
If I want to test this by using Jest, Enyzme, React-Testing-Library how should I proceed?
I have a component, its implementation details do not matter for this topic. Just be aware, that it contains
const [isBlocked, setIsBlocked] = useState(false);
And for my test, I want to set this to true.
describe('rendering DiffWindow', () => {
it("renders HeaderBar components without crash", () => {
const wrapper = shallow( < HeaderBar /> );
// HOW TO SET HERE THE STATE?
expect(wrapper.find('.header-is-there').exists()).toBeTruthy();
});
});
Upvotes: 0
Views: 1141
Reputation: 102672
Despite the implementation details, there are two situations in your problem:
1. State
is managed by the component itself
For boolean
state, the initial value is false
, followed by an API call to change its value to true
, or an event handler triggered by user interaction.
You need to set up a mock HTTP server to response the API call, or use fireEvent[eventName] to simulate user interaction. Assert component view changes when state changes.
2. State
is managed by the parent component
This case is mentioned by @blessenm. Generally, the state will have to be initialized by a prop passed from a parent component.
You can pass the prop with different values to change the view of the component.
Upvotes: 1