1

Hello everyone I started testing React app and ran into a problem - I can't test the components that are loaded from the server. Requests for uploading data are made via rtk-query, and I only know how to test this on axios. Code request:

    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']
        })
    })
})

The code of the component that is being loaded:

    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
ARSync
  • 11
  • 1
  • 4

1 Answers1

2

You can use a library like msw to mock your api - that's what we use in the Redux Toolkit codebase to test RTK Query.

phry
  • 35,762
  • 5
  • 67
  • 81