Unit test Redux Toolkit using React Testing Library guideline

Viewed 62

Can somebody learn me please how to unit test redux toolkit using react testing library? I tried to do like in the redux toolkit documentation, but no result. Also I've tried all solutions found, but maybe I'm doing something wrong.

my.service.ts

export const allHeadcountApiPaths = {
  fetchAllHeadcount: (params: IQueryParams) =>
    `${ApiUrlService.getTDS()}/rpc/v1/version/${params.versionId}/planned-headcount/view/with-relations${buildQuery(params)}`,
};

export const fetchBeginningHeadcount = createAsyncThunk('allHeadcount/fetchBeginningHeadcount', async (params: IQueryParams) => {
  const response = await api('GET', allHeadcountApiPaths.fetchAllHeadcount(params), {});
  return response.data;
});

my.slice.ts

export const initialState = new AllHeadcountState()

const allHeadcountSlice = createSlice({
  name: 'allHeadcount',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(fetchBeginningHeadcount.pending, state => {
        return requestListData<IAllHeadcountState, IHeadcount[]>({ ...state }, ['beginningHeadcount'])
      })
      .addCase(fetchBeginningHeadcount.fulfilled, (state, action) => {
        const { content, totalElements, totalPages } = action.payload
        return receiveListData<IAllHeadcountState, IHeadcount[]>({ ...state }, ['beginningHeadcount'], content, totalElements, totalPages)
      })
      .addCase(fetchBeginningHeadcount.rejected, (state, action) => {
        return errorListData<IAllHeadcountState, IHeadcount[]>({ ...state }, ['beginningHeadcount'], String(action.error.message))
      })
   },
})

export default allHeadcountSlice.reducer

my.provider.ts

   const render = (ui: ReactElement, { initialState = {}, initializedStore = store, ...renderOptions } = {}): RenderResult => {
  const Wrapper = ({ children }: PropsWithChildren): JSX.Element => {
    return <Provider store={initializedStore}>{children}</Provider>
  }
  return rtlRender(ui, { wrapper: Wrapper, ...renderOptions })
}

export * from '@testing-library/react'
export { render }

Also, I don't understand, should be written tests separately for service and slice, or one test covers them both?! Please help me to understand how these tests should work! Thanks in advance!

1 Answers

By that advice, you should just test your components that use Redux internally - not your Redux slice or your service in isolation.

Really just render your component in the test, simulate user interaction and see how it behaves. For the test it doesn't matter if you use Redux in the end or anything else - it should just work.

Related