简体   繁体   中英

How to test a Redux-enabled component with React Testing Library?

I'm struggling to test a React component without using the rerender function.

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. 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".

Is there a way to run this test without rerender ?

It is probably easier using the Provider as a wrapper:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM