mercredi 14 avril 2021

Mocking and testing onError with parameters

I am trying to mock useQuery, It has a certain parameter called onError. I am using it like this. It will be redirected after an error is encountered on the login page. I am basically token validation when the user makes a request.

export const useRedirectOnErrorMutation = <
    TData = unknown,
    TError = unknown,
    TVariables = void,
    TContext = unknown
>(
    redirectionPath: string,
    key: MutationKey,
    mutationFunction: MutationFunction<TData, TVariables>,
    options?: UseMutationOptions<TData, TError, TVariables, TContext>
): UseMutationResult<TData, TError, TVariables, TContext> => {
    const router = useRouter();
    console.log(useMutation);
    return useMutation(key, mutationFunction, {
        ...options,
        onError: (error) => {
            if (error?.response.status == "401" || error?.response.status == "422") {
                localStorage.removeItem("token");
                localStorage.removeItem("userId");
                router.push(redirectionPath);
            }
        },
    });
};

I have mocked it like this for now in the testing.

describe("(when api call gives error", () => {
        it("should return the response", () => {
            const push = jest.fn();

            let onError: (
                error: any,
                variables: any,
                context: any | undefined
            ) => Promise<void> | void;
            // @ts-ignore
            Router.useRouter = jest.fn(() => ({
                push: push,
            }));
            const mockData = { email: "test@test.com", password: "test@1234" };

            // @ts-ignore
            ReactQuery.useMutation = jest.fn(
                (
                    key: MutationKey,
                    mutationFunction: MutationFunction,
                    options: MutateOptions<
                        AxiosResponse<LoginResponse>,
                        AxiosError,
                        LoginValidationValues
                    >
                ) => {
                    console.log(options.onError.arguments);
                    onError = options.onError;
                    return {
                        mutate: jest.fn(() => mockData),
                        isLoading: false,
                    };
                }
            );
            const { result, rerender } = renderHook(() =>
                useRedirectOnErrorMutation("/auth/admin/login", "key", adminLoginAPI)
            );

            rerender();

            act(() => {
                onError({}, {}, {});
            });

            expect(result.current.mutate(mockData)).toEqual(mockData);
            expect(push).toHaveBeenCalled();
        });
    });
});

Any help would be appreciated! I am completely stuck here.

Aucun commentaire:

Enregistrer un commentaire