peter flanagan peter flanagan - 1 month ago 8
React JSX Question

update state of component using jest

I am trying to update the state of my component in jest.

What I am trying to do is check that when the state value of

updated
is set to
true
then the new props should not change the value of the state.
From answers I have read on here I assumed I could do the following to update the state of a component.

Game.setState({
updated: true
});


Here is my code below.

const props = {
goals: "0"
};

it("should should not update the state of goals when the value prop is changed if updated value in state is set to true", () => {
renderer.render(<Game {...props} />, div);

Game.setState({
updated: true
});

Game.componentWillReceiveProps({
goals: "2"
});

expect(Game.state.goals).toBe("0");
});

Answer Source

you can work with the instance

const gameRender = renderer.create(<Game {...props} />)
const gameInstance = gameRender.getInstance()

gameInstance.setState({ updated: true })

etc etc. your code references the constructor, not the instance.