反应钩子测试库的状态改变后,如何测试组件是否重新渲染

use*_*932 5 javascript testing unit-testing reactjs react-testing-library

我正在使用https://github.com/testing-library/react-hooks-testing-library来测试我的组件,但不确定如何检查我的组件在此测试中的状态更改后是否已重新渲染

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

Run Code Online (Sandbox Code Playgroud)

状态在 dispatch/click 事件后成功更新。我希望能够使用新状态重新渲染组件,但它仍然显示具有先前状态的原始组件

小智 0

await const divs = findAllByRole('div');
Run Code Online (Sandbox Code Playgroud)

findAllBy 是异步的,将等待找到它。如果 findAll 没有找到该值,则会抛出错误。https://testing-library.com/docs/react-testing-library/cheatsheet/