我正在尝试使用测试库在 fireEvent.click 之后检查 DOM 元素。我知道我需要在 fireEvent 之后等待,但不知道为什么简单地使用 await 不起作用?下面是用两种方式编写的相同测试——第一个失败,第二个通过。我不明白为什么第一个失败......非常感谢任何见解!
ps——我知道wait已被弃用,waitFor是首选,但是由于一些限制,我目前无法更新版本:(
失败的测试
// This test fails with the following error and warning:
// Error: Unable to find an element by: [data-test="name_wrapper"]
// Warning: An update to OnlinePaymentModule inside a test was not wrapped in act(...).
it('this is a failing test...why', async () => {
const { getByText, getByTestId } = render(<Modal {...props} />);
const button = getByText('open modal');
fireEvent.click(button);
const nameWrapper = await getByTestId('name_wrapper');
expect(
nameWrapper.getElementsByTagName('output')[0].textContent
).toBe('Jon Doe');
const numberWrapper = …Run Code Online (Sandbox Code Playgroud)我正在使用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)
状态在 …
javascript testing unit-testing reactjs react-testing-library