[英]How to test a Redux-enabled component with React Testing Library?
I'm struggling to test a React component without using the rerender
function.我正在努力在不使用重新rerender
function 的情况下测试 React 组件。
function renderDom(component, store) {
return {
...render(<Provider store={store}>{component}</Provider>),
store,
};
}
it('Should render a TimeEditor component and ensure the +/- buttons function correctly', async () => {
const store = configureStore(_initialState);
const spy = jest.spyOn(store, 'dispatch');
let component = {};
component = await renderDom(
<TimeEditor task={store.getState().stdForm.tasks[0]} />,
store
);
const { queryByTestId, findByTestId } = component
const minusButton = await findByTestId('subtract-minute');
const plusButton = await findByTestId('add-minute');
let duration = await findByTestId('start-service-duration');
expect(duration.innerHTML).toEqual('5');
expect(minusButton).toBeDisabled();
await fireEvent.click(plusButton);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith({
type: 'UPDATE_TASK_TIME',
payload: { id: '330d8081-6c32-4d62-b0f1-64cdd28d4b75', estimatedMinutes: 6 },
});
// rerender(
// <Provider store={store}>
// {<TimeEditor task={store.getState().stdForm.tasks[0]} />}
// </Provider>
// );
await waitForElement(() => findByTestId('start-service-duration'));
duration = await findByTestId('start-service-duration');
expect(duration.innerHTML).toEqual('6');
});
I've tried everything I can think of to get the code to work without the rerender
but nothing works.我已经尝试了所有我能想到的让代码在没有重新rerender
的情况下工作,但没有任何效果。 To be more precise, I know that the Redux Reducer is doing its job properly but this is not being reflected back in the component, so the "5" does not change to a "6".更准确地说,我知道 Redux 减速器正在正常工作,但这并没有反映在组件中,因此“5”不会变为“6”。
Is there a way to run this test without rerender
?有没有办法在不重新rerender
的情况下运行这个测试?
It is probably easier using the Provider as a wrapper:使用 Provider 作为包装器可能更容易:
function renderDom(component, store) {
const WithStore = ({children}) => <Provider store={store}>{children}</Provider>
return {
...render(component, {wrapper: WithStore}),
store,
};
}
That way you don't need to pay any attention to the provider on rerender.这样您就无需在重新渲染时关注提供者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.