Skip to content

Commit

Permalink
test: fetchPopulation関数のユニットテストを追加
Browse files Browse the repository at this point in the history
  • Loading branch information
crab85193 committed Dec 17, 2024
1 parent 7f4ced2 commit 2a90a74
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/tests/population.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import axios from "axios";
import { fetchPopulation } from "../api/population";
import { PopulationCategory } from "../types/population";

jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios>;

describe("fetchPopulation", () => {
it("正常に人口データを取得できる", async () => {
const mockData: PopulationCategory[] = [
{
label: "年少人口",
data: [{ year: 1960, value: 1681479, rate: 33.37 }],
},
];

const mockResponse = {
message: "success",
result: {
boundaryYear: 2020,
data: mockData,
},
};

mockedAxios.get.mockResolvedValue({ status: 200, data: mockResponse });

const prefCode = "1";

const result = await fetchPopulation(prefCode);

expect(result).toEqual(mockData);
expect(mockedAxios.get).toHaveBeenCalledWith(
`${process.env.REACT_APP_YUMEMI_API_URL}/population/${prefCode}`,
{
headers: {
"X-API-KEY": process.env.REACT_APP_YUMEMI_API_KEY!,
},
}
);
});

it("APIがエラーを返した場合、エラーをスローする", async () => {
mockedAxios.get.mockRejectedValue(new Error("API Error"));

const prefCode = "1";

await expect(fetchPopulation(prefCode)).rejects.toThrow(
"Error fetching population data: Error: API Error"
);
expect(mockedAxios.get).toHaveBeenCalledWith(
`${process.env.REACT_APP_YUMEMI_API_URL}/population/${prefCode}`,
{
headers: {
"X-API-KEY": process.env.REACT_APP_YUMEMI_API_KEY!,
},
}
);
});
});

0 comments on commit 2a90a74

Please sign in to comment.