Testing useCounter Hook actions

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:

  1. Write a new test function, as shown in the following code:
test('should increment counter', () => {
const { result } = renderHook(() => useCounter())
  1. Call the increment function of the Hook within the act function:
    act(() => result.current.increment())
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.109