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
I edited this part =>
and work.
just add a
return
statement tobuildingGeo
function, so instead of:It will be:
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.