reactjs 如何测试react hooks状态更改后组件是否重新呈现测试库

m0rkklqb  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(147)

我正在使用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

在分派/单击事件之后,状态成功更新。我希望能够使用新状态重新呈现组件,但它仍然显示具有先前状态的原始组件

qhhrdooz

qhhrdooz1#

await const divs = findAllByRole('div');

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

相关问题