redux 使用rtk-query请求测试组件

irtuqstp  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(161)

大家好,我开始测试React应用时遇到了一个问题--我无法测试从服务器加载的组件。上传数据的请求是通过rtk-query发出的,我只知道如何在axios上测试。代码请求:

export const postApi = createApi({
    reducerPath: 'getAllChallenges',
    baseQuery: fetchBaseQuery({ baseUrl: urlDomain }),
    tagTypes: ['Challenge'],
    endpoints: (build) => ({
        getAllChallenges: build.query<IChallenge[], string>({
            query: () => ({
                url: urlGetChallenges,
            }),
            providesTags: res => ['Challenge']
        }),
        getChallengeById: build.query<IChallengeDetails, string>({
            query: (id: string) => ({
                url: urlGetChallengeById + id,
                headers: {
                    token: localStorage.getItem('token') || '',
                    signature: localStorage.getItem('signature') || '',
                    'Content-Type': 'application/json',
                }
            }),
            providesTags: res => ['Challenge']
        }),
        getChallengeMembers: build.query<IChallengeMember[], string>({
            query: (id: string) => ({
                url: urlGetChallengeMembers + id,
                headers: {
                    token: localStorage.getItem('token') || '',
                    signature: localStorage.getItem('signature') || '',
                    'Content-Type': 'application/json',
                }
            }),
            providesTags: res => ['Challenge']
        }),
        acceptChallenge: build.mutation<IChallengeMember[], string>({
            query: (id: string) => ({
                url: urlAcceptChallenge + id,
                headers: {
                    token: localStorage.getItem('token') || '',
                    signature: localStorage.getItem('signature') || '',
                    'Content-Type': 'application/json',
                }
            }),
            invalidatesTags: ['Challenge']
        })
    })
})

正在加载的组件的代码:

const Challenges: FC = () => {
    const { data: challenges, isLoading } = postApi.useGetAllChallengesQuery('')
    const { loginStatus } = useTypedSelector(state => state.login)
    return (
        <MainWrapper dataTestid='challenges-page'>
            <Popup />
            {loginStatus && <CreateChallenge />}
            {isLoading && <Loader />}
            {challenges && challenges.map(challenge =>
                <ChallengesItem data-testid='challenge-item' key={challenge.challenge_id} challenge={challenge} />
            )}
        </MainWrapper>
    )
}

export default Challenges
arknldoa

arknldoa1#

您可以使用像msw这样的库来模拟您的api -这是我们在Redux Toolkit代码库中用来测试RTK Query的。

相关问题