Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(test): mock methods not being called for GlobalAPIService #1052

Merged
merged 4 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 23 additions & 18 deletions app/src/backend/GlobalAPIService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,29 @@ import { logger } from "@/services/logger";

export type GrowthRatesResponse = Omit<EmissionsForecastData, "forecast">;

export const getGrowthRatesFromOC = async (
locode: string,
forecastYear: number,
): Promise<GrowthRatesResponse | undefined> => {
try {
const URL = `${GLOBAL_API_URL}/api/v0/ghgi/emissions_forecast/city/${encodeURIComponent(locode)}/${forecastYear}`;
const response = await fetch(URL);
logger.info(`${URL} Response Status: ${response.status}`);
const data = await response.json();
if (response.status !== 200) {
export class GlobalAPIService {
public static async fetchGrowthRates(
locode: string,
forecastYear: number,
): Promise<GrowthRatesResponse | undefined> {
try {
const URL = `${GLOBAL_API_URL}/api/v0/ghgi/emissions_forecast/city/${encodeURIComponent(locode)}/${forecastYear}`;
const response = await fetch(URL);
logger.info(`${URL} Response Status: ${response.status}`);
if (response.status !== 200) {
return undefined;
}

const data = await response.json();
return {
...data,
growthRates: data.growth_rates,
};
} catch (error) {
logger.error(`Error fetching growth rates: ${error}`);
return undefined;
}
return {
...data,
growthRates: data.growth_rates,
};
} catch (error) {
console.error(`Error fetching growth rates: ${error}`);
return undefined;
}
};
}

export default GlobalAPIService;
12 changes: 9 additions & 3 deletions app/src/backend/ResultsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { ActivityDataByScope, GroupedActivity } from "@/util/types";
import Decimal from "decimal.js";
import { bigIntToDecimal } from "@/util/big_int";
import createHttpError from "http-errors";
import { getGrowthRatesFromOC } from "./GlobalAPIService";
import GlobalAPIService from "./GlobalAPIService";
import { Inventory } from "@/models/Inventory";

function multiplyBigIntByFraction(
Expand Down Expand Up @@ -751,7 +751,7 @@ export async function getEmissionResults(inventory: string): Promise<{
}

export const getEmissionsForecasts = async (inventoryData: Inventory) => {
const OCResponse = await getGrowthRatesFromOC(
const OCResponse = await GlobalAPIService.fetchGrowthRates(
inventoryData.city.locode!,
inventoryData.created!.getFullYear(),
);
Expand Down Expand Up @@ -782,7 +782,13 @@ export const getEmissionsForecasts = async (inventoryData: Inventory) => {
totalEmissionsBySector.forEach((emissionsInSector) => {
const previousYear = year - 1;
const referenceNumber = emissionsInSector.reference_number;
const growthRate = growthRates[year][referenceNumber];
const growthRate = growthRates?.[year]?.[referenceNumber];
if (!growthRate) {
throw new createHttpError.InternalServerError(
`Failed to find growth rate for sector ${referenceNumber} in year ${year} in city ${inventoryData.city.locode!}`,
);
}

projectedEmissions[year][referenceNumber] = multiplyBigIntByFraction(
projectedEmissions[previousYear][referenceNumber],
1 + growthRate,
Expand Down
27 changes: 13 additions & 14 deletions app/tests/api/emissions_forecast.jest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,22 @@ import {
} from "@/util/enums";
import { City } from "@/models/City";
import { Inventory } from "@/models/Inventory";
import { GrowthRatesResponse } from "@/backend/GlobalAPIService";
import GlobalAPIService from "@/backend/GlobalAPIService";

const locode = "XX_SUBCATEGORY_CITY";

// TODO UNSKIP when we can mock getGrowthRatesFromOC
describe.skip("Emissions Forecast API", () => {
describe("Emissions Forecast API", () => {
let city: City;
let inventory: Inventory;
let mockGrowthRates: GrowthRatesResponse | undefined;

jest
.spyOn(GlobalAPIService, "fetchGrowthRates")
.mockImplementation((locode, forecastYear) => {
return Promise.resolve(mockGrowthRates);
});

beforeAll(async () => {
setupTests();
await db.initialize();
Expand Down Expand Up @@ -51,13 +60,7 @@ describe.skip("Emissions Forecast API", () => {
});

it("should calculate projected emissions correctly", async () => {
jest.mock("@/backend/GlobalAPIService", () => {
return {
getGrowthRatesFromOC: jest
.fn()
.mockImplementation(() => growth_rates_response),
};
});
mockGrowthRates = growth_rates_response;
const req = mockRequest();
const result = await getResults(req, {
params: { inventory: inventory.inventoryId },
Expand All @@ -67,11 +70,7 @@ describe.skip("Emissions Forecast API", () => {
});

it("should handle empty growth factors", async () => {
jest.mock("@/backend/GlobalAPIService", () => {
return {
getGrowthRatesFromOC: jest.fn().mockImplementation(() => undefined),
};
});
mockGrowthRates = undefined;
const req = mockRequest();
const result = await getResults(req, {
params: { inventory: inventory.inventoryId },
Expand Down
Loading