網站搜尋

reactjs - 使用 React Testing Library 單元測試 Redux Toolkit 指南


有人可以教我如何使用 React Testing Library 對 Redux Toolkit 進行單元測試嗎?我試過按照 Redux Toolkit 文件上的方法,但沒有結果。我也試過所有找到的解決方案,但可能我做錯了什麼。

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 }

另外,我不明白,應該分別為 service 和 slice 寫測試,還是用一個測試涵蓋它們兩個?!請幫我理解這些測試應該如何運作!提前感謝!

答案#1

根據那個建議,你應該只測試內部使用 Redux 的組件,而不是單獨測試你的 Redux 切片或服務。

實際上只需在測試中渲染你的元件,模擬用戶互動並觀察它的行為。對於測試來說,最終是否使用 Redux 或其他東西並不重要——它應該可以正常運作。