Skip to content

Commit

Permalink
Added tests and cleaned up files
Browse files Browse the repository at this point in the history
  • Loading branch information
kotva006 committed Oct 19, 2023
1 parent 5f2f723 commit 7503776
Show file tree
Hide file tree
Showing 7 changed files with 275 additions and 18 deletions.
266 changes: 266 additions & 0 deletions apps/site/assets/ts/stop/__tests__/DeparturesAndMapShuttleTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
import React from "react";
import { screen, waitFor } from "@testing-library/react";
import DeparturesAndMap from "../components/DeparturesAndMap";
import { Stop, Route } from "../../__v3api";
import { renderWithRouter } from "./helpers";
import * as useSchedules from "../../hooks/useSchedules";
import { ScheduleWithTimestamp } from "../../models/schedules";
import { add } from "date-fns";
import * as useVehiclesChannel from "../../hooks/useVehiclesChannel";
import { FetchStatus } from "../../helpers/use-fetch";
import * as usePredictionsChannel from "../../hooks/usePredictionsChannel";
import { PredictionWithTimestamp } from "../../models/predictions";

const stop = {
id: "test-stop",
name: "Test Stop",
latitude: 42.3519,
longitude: 71.0552
} as Stop;
const now = Date.now();

const crRoute = {
type: 2,
name: "Framingham/Worcester Line",
long_name: "Framingham/Worcester Line",
line: {
type: "line",
id: "line-Worcester"
},
id: "CR-Worcester",
direction_names: {
"0": "Outbound",
"1": "Inbound"
},
direction_destinations: {
"0": "Worcester",
"1": "South Station"
},
description: "commuter_rail"
};
const railReplacementRoute = {
type: 3,
name: "Worcester Line Shuttle",
long_name: "Ashland - Framingham",
line: {
type: "line",
id: "line-Worcester"
},
id: "Shuttle-AshlandFramingham",
direction_names: {
"0": "Outbound",
"1": "Inbound"
},
direction_destinations: {
"0": "Worcester",
"1": "South Station"
},
description: "rail_replacement_bus"
};
const rapidTransitRoute = {
type: 1,
name: "Test Rapid Transit",
long_name: "Test Rapid Transit Line",
line: {
type: "line",
id: "line-rapid-transit"
},
id: "Test-Rapid-Line",
direction_names: {
"0": "Outbound",
"1": "Inbound"
},
direction_destinations: {
"0": "Test North Station",
"1": "Test South Station"
},
description: "rapid_transit"
};

const rapidTransitShuttleRoute = {
type: 3,
name: "Test Rapid Transit (Shuttle)",
long_name: "Test Rapid Transit (Shuttle) Line",
line: {
type: "line",
id: "line-rapid-transit"
},
id: "Shuttle-Test-Rapid-Line",
direction_names: {
"0": "Outbound",
"1": "Inbound"
},
direction_destinations: {
"0": "Test North Station",
"1": "Test South Station"
},
description: "rail_replacement_bus"
};

const groupedRoutePatterns = {
"Shuttle-AshlandFramingham": {
"Ashland (Shuttle)": [
{
headsign: "Ashland (Shuttle)",
id: "ashland-shuttle",
route_id: railReplacementRoute.id,
direction_id: 1,
representative_trip_polyline: {
id: "1"
}
}
]
},
"CR-Worcester": {
"North Station": [
{
headsign: "North Station",
id: "north-station",
route_id: crRoute.id,
direction_id: 1,
representative_trip_polyline: {
id: "2"
}
}
],
"South Station": [
{
headsign: "South Station",
id: "south-station",
route_id: crRoute.id,
direction_id: 1,
representative_trip_polyline: {
id: "3"
}
}
]
}
};

const groupedRapidTransitRoutePatterns = {
"Shuttle-Test-Rapid-Line": {
"Rapid (Shuttle)": [
{
headsign: "Rapid (Shuttle)",
id: "rapid-shuttle",
route_id: rapidTransitShuttleRoute.id,
direction_id: 1,
representative_trip_polyline: {
id: "1"
}
}
]
},
"Test-Rapid-Line": {
"Test North Station": [
{
headsign: "North Station",
id: "north-station",
route_id: rapidTransitRoute.id,
direction_id: 1,
representative_trip_polyline: {
id: "2"
}
}
]
}
};

jest.mock("../components/StopMapRedesign", () => ({
__esModule: true,
default: () => <div>Stop Map</div>
}));

describe("DeparturesAndMap", () => {
afterAll(() => {
jest.restoreAllMocks();
});

it("should merge the rail replacement shuttles into the commuter rail cards", async () => {
jest.spyOn(useVehiclesChannel, "default").mockReturnValue([]);
jest
.spyOn(usePredictionsChannel, "default")
.mockReturnValue([] as PredictionWithTimestamp[]);

const schedules = [
{
route: crRoute,
stop: stop,
trip: { id: "1", headsign: "Worcester", direction_id: 1 },
time: add(now, { minutes: 10 })
},
{
route: railReplacementRoute,
stop: stop,
trip: { id: "2", headsign: "Worcester (Shuttle)", direction_id: 0 },
time: add(now, { minutes: 15 })
}
] as ScheduleWithTimestamp[];

jest
.spyOn(useSchedules, "useSchedulesByStop")
.mockReturnValue({ status: FetchStatus.Data, data: schedules });

const routes = [crRoute, railReplacementRoute] as Route[];

renderWithRouter(
<DeparturesAndMap
routes={routes}
stop={stop}
alerts={[]}
setPredictionError={jest.fn()}
/>,
[],
groupedRoutePatterns
);

await waitFor(() => {
expect(screen.getByText("Ashland (Shuttle)")).toBeInTheDocument();
expect(screen.queryByText("Worcester Line Shuttle")).toBeNull();
});
});

it("should not show the rapid tranist shuttle routes", async () => {
jest.spyOn(useVehiclesChannel, "default").mockReturnValue([]);
jest
.spyOn(usePredictionsChannel, "default")
.mockReturnValue([] as PredictionWithTimestamp[]);

const schedules = [
{
route: rapidTransitRoute,
stop: stop,
trip: { id: "1", headsign: "Worcester", direction_id: 1 },
time: add(now, { minutes: 10 })
},
{
route: rapidTransitShuttleRoute,
stop: stop,
trip: { id: "2", headsign: "Worcester (Shuttle)", direction_id: 0 },
time: add(now, { minutes: 15 })
}
] as ScheduleWithTimestamp[];

jest
.spyOn(useSchedules, "useSchedulesByStop")
.mockReturnValue({ status: FetchStatus.Data, data: schedules });

const routes = [rapidTransitRoute, rapidTransitShuttleRoute] as Route[];

renderWithRouter(
<DeparturesAndMap
routes={routes}
stop={stop}
alerts={[]}
setPredictionError={jest.fn()}
/>,
[],
groupedRapidTransitRoutePatterns
);

await waitFor(() => {
expect(screen.getByText("Test North Station")).toBeInTheDocument();
expect(screen.queryByText("Test Rapid Transit (Shuttle)")).toBeNull();
});
});
});
6 changes: 0 additions & 6 deletions apps/site/assets/ts/stop/__tests__/DeparturesAndMapTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,6 @@ beforeEach(() => {
.spyOn(useSchedules, "useSchedulesByStop")
.mockReturnValue({ status: FetchStatus.Data, data: schedules });
jest.spyOn(useVehiclesChannel, "default").mockReturnValue([]);
jest.mock("react-router-dom", () => ({
__esModule: true,
useLoaderData: () => {
return TEST_LOADER_VALUE;
}
}));
});

afterAll(() => {
Expand Down
6 changes: 4 additions & 2 deletions apps/site/assets/ts/stop/__tests__/helpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,12 @@ const testLoader = () => {
};

export const TEST_LOADER_VALUE = testLoader();
const loaderMock = jest.fn().mockReturnValue(TEST_LOADER_VALUE);
// via https://webup.org/blog/how-to-avoid-mocking-in-react-router-v6-tests/
//@ts-ignore
export function renderWithRouter(children, routes = []) {
export function renderWithRouter(children, routes = [], loaderData?) {
const loaderMock = jest
.fn()
.mockReturnValue(loaderData ? loaderData : TEST_LOADER_VALUE);
const options = isValidElement(children)
? { element: children, path: "/", loader: loaderMock }
: children;
Expand Down
2 changes: 1 addition & 1 deletion apps/site/assets/ts/stop/components/DepartureCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const DepartureCard = ({
}),
[routePatternsByHeadsign]
);
// console.log(sortedRoutePatternsByHeadsign)

return (
<li className="departure-card">
<a
Expand Down
9 changes: 4 additions & 5 deletions apps/site/assets/ts/stop/components/DeparturesAndMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import React, {
useRef,
useState
} from "react";
import { concat, filter, orderBy, uniqBy } from "lodash";
import { cloneDeep, concat, filter, orderBy, uniqBy } from "lodash";
import { clearAllBodyScrollLocks, disableBodyScroll } from "body-scroll-lock";
import { useLoaderData } from "react-router-dom";
import { Alert, Route, Stop } from "../../__v3api";
Expand Down Expand Up @@ -87,8 +87,8 @@ const updateDepartureInfos = (
const updateRoutePatterns = (
groupedRoutePatterns: GroupedRoutePatterns,
routeIdMap: { [key: string]: Route }
) => {
let updatedPatterns = groupedRoutePatterns;
): GroupedRoutePatterns => {
const updatedPatterns = cloneDeep(groupedRoutePatterns);
Object.keys(groupedRoutePatterns).forEach(key => {
if (routeIdMap[key]) {
const routeIdToUpdate = routeIdMap[key].id;
Expand Down Expand Up @@ -122,7 +122,6 @@ const DeparturesAndMap = ({
const [realtimeAlerts, setRealtimeAlerts] = useState<Alert[]>([]);

const mappedRouteIds = mapRouteIds(routes);
console.log(routes);
const updatedDepartureInfos = updateDepartureInfos(
departureInfos,
mappedRouteIds
Expand Down Expand Up @@ -255,7 +254,7 @@ const DeparturesAndMap = ({
/>
)}
</div>
<div className={`stop-map hidden-sm-down`}>
<div className="stop-map hidden-sm-down">
<StopMapRedesign
stop={stop}
lines={
Expand Down
1 change: 0 additions & 1 deletion apps/site/assets/ts/stop/components/StopPageDepartures.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { filter, groupBy, sortBy } from "lodash";
import React, { ReactElement, useState } from "react";
import { useLoaderData } from "react-router-dom";
import { Alert, Route } from "../../__v3api";
import DeparturesFilters, { ModeChoice } from "./DeparturesFilters";
import { isRailReplacementBus, modeForRoute } from "../../models/route";
Expand Down
3 changes: 0 additions & 3 deletions apps/site/assets/ts/stop/components/StopPageRedesign.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,12 @@ const StopPageRedesign = ({
const [hasPredictionError, setPredictionError] = useState(false);
const stopResult = useStop(stopId);
const groupedRoutePatterns = useLoaderData() as GroupedRoutePatterns;
// console.log(groupedRoutePatterns)
const routesResult = useRoutes(Object.keys(groupedRoutePatterns || []));
const alertsForStopResult = useAlertsByStop(stopId);
const facilities = useFacilitiesByStop(stopId);
const routes = routesResult.data || [];
const alertsForRoutesResult = useAlertsByRoute(routes.map(r => r.id));

// console.log(routesResult.data)

if (
[stopResult.status, routesResult.status, facilities.status].includes(
FetchStatus.Error
Expand Down

0 comments on commit 7503776

Please sign in to comment.