DEV Community

Discussion on: Mocking redux useSelector-hook

Collapse
 
markerikson profile image
Mark Erikson • Edited

What do you mean by "did not allow that"?

RTL's docs specifically show how to use it with React-Redux:

function renderWithRedux(
  ui,
  { initialState, store = createStore(reducer, initialState) } = {}
) {
  return {
    ...render(<Provider store={store}>{ui}</Provider>),
    // adding `store` to the returned utilities to allow us
    // to reference it in our tests (just try to avoid using
    // this to test implementation details).
    store,
  }
}

// then, in a test:
const { getByTestId, getByText } = renderWithRedux(<Counter />)
Thread Thread
 
fredrikbergqvist profile image
Fredrik Bergqvist

Well to be honest I did add it to the render method, noticed that I got an error and took the other way out :)

Thread Thread
 
timrohrer profile image
tim.rohrer

Another dev (way more experienced than me) also mocks useSelector.

I would like to see the "official" way work, but so far I'm still stuck.

In my component, a useSelector that includes the callback definition works. However, any useSelector that requires an imported callback seems to remain undefined.

This works:

  let demoTrip = useSelector(
    (state: RootState) => state.trips.allTrips[demoTripId]
  );

This returns undefined:

import { selectChosenMappingService } from '../system/systemSlice';  
...
const mappingServiceName = useSelector(selectChosenMappingService);

And from my slice:

export const selectChosenMappingService = (
  state: SystemState
): MappingService => state.chosenMappingService;

I remain confused.

Thread Thread
 
timrohrer profile image
tim.rohrer

I am happy to report that my issue was a mistake in my definitions of my selector functions in my slice. Turns out I needed to type as RootState and then include the reducer in the return (i.e., state.system.chosenMappingService).