0
votes

I have a component named AddEditVehicle which renders when the route is /vehicle/:vehicleId/edit.

I need to test the React lifecycles of this component. So I have used Enzyme mount to render my component in the unit test in the following way.

beforeEach(async () => {
  wrapper = await mount(
    <BrowserRouter>
      <Provider store={store}>
        <AddEditVehicle match={{ params: { vehicleId } }} />
         </Provider>
       </BrowserRouter>
      );
     await wrapper.update();
});

this wrapper fails to pass the required params making following specs to fail.

it("expect `isEditMode` value to set", () => {
      const componentState = wrapper.find("AddEditVehicle").instance().state;
      expect(componentState.isEditMode).toEqual(true);
});

Versions :

  • react ^16.4.2
  • react-router ^4.3.1
  • jest ^23.5.0
  • enzyme ^3.4.4
1
You don't want to test with real router. Memory router is supposed to be used in unit tests. - Estus Flask
I have tried with <MemoryRouter initialEntries={["/vehicle/2/edit"]} initialIndex={0}>, this is the console output when a print the match props in console { path: '/', url: '/', params: {}, isExact: false} - Satyaki
@Satyaki you want to check state right ? - Javed Shaikh
try to use expect(wrapper.state().isEditMode).toBeTruthy() - yohaiz
@Salahuddin No and Yes, actually, in my component, I'm calling an API on the basis of passed id at the URL. and setting the state variable to edit mode true. So, I need to have access on id as well as the state. In the present scenario, state does not reflect the correct edit state as it's unable to check the id of url - Satyaki

1 Answers

0
votes

The problem with my approach was my Component was part of a Route but still, I was wrapping the component with withRouter which is redundant. So, in the unit test when I was passing the Route match details it was getting overridded. Thus, removing the withRouter made the solution work.