Files
time_to_leave/src/hooks/__tests__/useBikeRoute.test.ts
T
fegger ce2a900545 Add correlation IDs and tests for monitoring
Generate short UUIDs in API route catch blocks to aid debugging.
Update existing API tests to assert the correlation ID. Add unit
tests for `useJourneys` and `useBikeRoute` hooks, and component
tests for `EventCard` and `CalendarView`.
2026-05-10 08:59:17 +02:00

71 lines
2.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { useBikeRoute } from "../useBikeRoute";
beforeEach(() => {
vi.restoreAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("useBikeRoute", () => {
it("does nothing when coordinates are missing", async () => {
const { result } = renderHook(() => useBikeRoute(undefined, undefined, 48.21, 16.38));
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.bikeRoute).toBeNull();
expect(result.current.error).toBeNull();
});
it("returns bike route when API succeeds", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
json: async () => ({
distance: 1500,
duration: 300,
steps: [
{ name: "Start", distance: 100, duration: 10, instruction: "Go straight" },
],
}),
} as Response);
const { result } = renderHook(() =>
useBikeRoute(48.2082, 16.3738, 48.21, 16.38),
);
expect(result.current.loading).toBe(true);
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.bikeRoute).not.toBeNull();
expect(result.current.bikeRoute?.distance).toBe(1500);
expect(result.current.bikeRoute?.duration).toBe(300);
expect(result.current.error).toBeNull();
});
it("sets error when API fails", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: false,
status: 500,
} as Response);
const { result } = renderHook(() =>
useBikeRoute(48.2082, 16.3738, 48.21, 16.38),
);
await waitFor(() => expect(result.current.error).toBeTruthy());
expect(result.current.bikeRoute).toBeNull();
});
it("sets error when fetch throws", async () => {
vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Network error"));
const { result } = renderHook(() =>
useBikeRoute(48.2082, 16.3738, 48.21, 16.38),
);
await waitFor(() => expect(result.current.error).toBe("Network error"));
});
});