[英]Unit test Redux Toolkit using React Testing Library guideline
有人可以教我如何使用反应测试库对 redux 工具包进行单元测试吗? 我尝试在 redux 工具包文档中这样做,但没有结果。 我也尝试了所有找到的解决方案,但也许我做错了什么。
我的.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;
});
我的.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
我的.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 }
另外,我不明白,应该为服务和切片分别编写测试,还是一个测试同时涵盖它们?! 请帮助我了解这些测试应该如何工作! 提前致谢!
根据该建议,您应该只测试在内部使用 Redux 的组件 - 而不是您的 Redux 切片或孤立的服务。
真的只是在测试中渲染你的组件,模拟用户交互并查看它的行为。 对于测试,无论您最终使用 Redux 还是其他任何东西都没有关系 - 它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.