reactjs - Pokyny na jednotkové testovanie Redux Toolkitu pomocou React Testing Library


Môže mi niekto, prosím, naučiť, ako testovať redux toolkit pomocou react testing library? Skúšal som to robiť podľa dokumentácie redux toolkit, ale žiaden výsledok. Tiež som vyskúšal všetky nájdené riešenia, ale možno robím niečo zle.

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

moj.poskytovateľ.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 }

Tiež tomu nerozumiem, mali by byť písomné testy samostatne pre službu a modul, alebo jeden test pokrýva oboje?! Prosím, pomôžte mi pochopiť, ako by tieto testy mali fungovať! Vopred ďakujem!

Odpoveď č. 1

Podľa tej rady by ste mali testovať len svoje komponenty, ktoré interné používajú Redux - nie váš Redux slice alebo vašu službu izolovane.

Naozaj len vykreslite svoj komponent v teste, simulujte používateľskú interakciu a pozrite sa, ako sa správa. Pre test nie je dôležité, či nakoniec použijete Redux alebo niečo iné - malo by to jednoducho fungovať.