How Can I Use nock with react-query in a React 18 Project for Testing?

214 Views Asked by At

I am trying to test a custom hook that uses react-query for data fetching in a React 18 project. The API call is mocked using nock, but I am facing issues: the result.current remains undefined, and the query stays in the loading state. I've already consulted the React Query testing documentation, but it hasn't been helpful for solving this problem.

my source code:

import { getUserProfileAPI } from "@/api/userProfile";
import { createQueryProviderWrapper } from "@/test/index";
import { useQuery } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import nock from "nock";

// Custom hook using react-query
const useGetUserProfileAPIQuery = () => {
  return useQuery(["tokenKey"], getUserProfileAPI); // getUserProfileAPI uses fetch('v1/me')
};

// Helper function to set up the hook
const setupHook = () => {
  return renderHook(() => useGetUserProfileAPIQuery(), {
    wrapper: createQueryProviderWrapper(),
  });
};

// Test suite
describe("useGetUserProfileAPIQuery", () => {
  test("should fetch user profile and have correct nickname", async () => {
    // Mocking the API response using nock
    nock("https://api.example.com")
      .get("/v1/me")
      .reply(200, {
        data: {
          id: 1,
          firstName: "/value from the api",
        },
      });

    // Setting up the hook
    const { result } = setupHook();

    // Trying to access result.current
    await waitFor(() => {
      console.log("result: => ", result.current.status); // Keeps returning isLoading
      console.log("result: => ", result.current.data); // Keeps returning undefined
    });
  });
});

Specific Issues

  1. Why is result.current undefined?
  2. Why does the query status remain in loading state?
  3. Am I missing something in the setup?

Any guidance would be highly appreciated!

0

There are 0 best solutions below