how to test if component rerenders after state change for react hooks testing library
Asked Answered
E

1

12

I'm using https://github.com/testing-library/react-hooks-testing-library to test my component but not sure how to check if my component has been re-rendered after a state change in this test

const { container, getAllByText, getAllByRole, queryByLabelText, getByText, getByLabelText } = renderNavBar(
    initialState,
    dispatchMock,
);

// get all divs
let divs = getAllByRole('div');
.
.
.

const { result, waitForNextUpdate } = renderHook(() => useReducer(Reducer, initialState));
const [ , dispatch ] = result.current;

act(() => {
    dispatch({ type: 'SET_ACTIVE_LINK', payload: 'about' });
    fireEvent.click(getByText('home'));
});


// get all divs after the state change,
divs = getAllByRole('div');  // <---- this still has the NavBar component with the old state

The state successfully updates after the dispatch/click event. I want to be able to get the component re-rendered with new state but it's still showing the original component with the previous state

Ezar answered 25/6, 2020 at 0:18 Comment(4)
Typically you need to wait for the UI to update, check async. Also, check out user events, it handles using events a little better than the baked in generic fire event.Jinnah
so you shouldn't explicitly have to call rerender with the new state? the component should just rerender automatically after the state changes?Ezar
No, I wouldn't think you would need to rerender anything forcefully. Also, looks like the docs I linked earlier are out-of-date, the underlying DOM testing library async docs are a little more informative. Some functionality has been deprecated it seems.Jinnah
I was writing up a test application for myself and ran into a similar issue. I had to forcefully re-render the application in order to get the UI to show an update. Answer here: https://mcmap.net/q/545249/-react-testing-library-39-s-waitfor-not-workingWheatley
M
-1
await const divs = findAllByRole('div');

findAllBy is async and will wait to find it. findAll will throw an error if it doesn't find the value. https://testing-library.com/docs/react-testing-library/cheatsheet/

Mendelssohn answered 10/11, 2022 at 22:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.