Skip to content
Advertisement

How to use ReactTestUtils to Simulate onChange event to update State

I want to run unit tests on a simple score keeping component in React. My component has two State values, score and newPoints. An input element specifies the newPoints to add, and a button adds that to the score.

Score keeping component

Game.js:

JavaScript

Problem: The component works fine in my browser but I can’t seem to get the unit tests working.

The ReactTestUtils.Simulate function in the test script successfully calls my component’s handlePointsChange and the valueAsNumber received is correct. However, when my test script simulates a mouse click via dispatchEvent, the value of newPoints in handleAdd is still zero. It seems as though the value of newPoints state hasn’t been updated yet, even after calling setNewPoints

Game.test.js

JavaScript

Console log:

JavaScript

Could anyone point me in the right direction to get this unit test to work?

Advertisement

Answer

I managed to get the tests working by putting each event in separate act() blocks.

I guess this way it ensures that everything within the first act() block will finish rendering before executing the second act() block.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement