2

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I will try to do like this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.