Using the act function from the React Hooks Testing Library, we can execute functions from the Hook and then check the new result.
Let's now test actions of our Counter Hook:
- Write a new test function, as shown in the following code:
test('should increment counter', () => {
const { result } = renderHook(() => useCounter())
- Call the increment function of the Hook within the act function:
act(() => result.current.increment())
- Finally, we check whether the new count is now 1:
expect(result.current.count).toBe(1)
})
As we can see, we can simply use the act function to trigger actions in our Hook and then test the value just like we did before.