skip to Main Content

Here I want to test the data output on the endpoint.

My test:

import { render, screen } from "@testing-library/react";
import axios from "axios";
import CompBuildingGeo from "./components/CompBuildingGeo";
import { getBuildingGEO } from "../../service/building";

const buildingGeo = async () => {
  try {
    const result = await getBuildingGEO();
    console.log(result?.map((total) => total.total_building));
  } catch (error) {
    console.log("salah");
  } finally {
    console.log("none");
  }
};

describe("Component Building", () => {

  test("CompBuildingGeo API", async () => {
    render(<CompBuildingGeo />);
    jest.spyOn(axios, "get").mockReturnValue({
      data: [
        {
          total_building: "76915222",
        },
      ],
    });
    const result = await buildingGeo();
    expect(result).toBe("76915222");
  });
});

However, when I npm run test, this error appears:

Expected: "76915222"
Received: undefined

  35    |      });
  36    |    const result = await buildingGeo();
> 37    |   expect(result?.map((total) => total.total_buildings)).toBe("76915222");
        |   
  38    |  });
  39    |});

What is the cause of the error?

2

Answers


  1. Chosen as BEST ANSWER

    I edited this part =>

    const buildingGeo = async () => {
      try {
        const result = await axios.get(
          `${process.env.REACT_APP_SERVICE_DISTRICT}/buildingCountGeoSettleAll`,
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        );
        return result;
      } catch (error) {
        console.log("salah");
      } finally {
        console.log("none");
      }
    };
    

    and work.


  2. just add a return statement to buildingGeo function, so instead of:

      try {
        const result = await getBuildingGEO();
        console.log(result?.map((total) => total.total_building));
      } catch (error) {
        console.log("salah");
      } finally {
        console.log("none");
      }
    };
    

    It will be:

    const buildingGeo = async () => {
      try {
        const result = await getBuildingGEO();
        console.log(result?.map((total) => total.total_building));
        return result;
      } catch (error) {
        console.log("salah");
      } finally {
        console.log("none");
      }
    };
    

    I’m not 100% percent sure, but you might have to access the data property before returning (result.data), but the code above should work.

    The undefined you were getting was happening because your function was not returning anything.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search