From fd1ad31bb541ee53d7feecb5ec56c9aa5e4398ab Mon Sep 17 00:00:00 2001 From: Thomas Heartman Date: Mon, 3 Feb 2025 14:29:07 +0100 Subject: [PATCH] fix: make traffic usage test more robust by using this month's actual numbers (#9193) The test was breaking because it assumed a month would have at least 30 days. Because the test relies on the current month, this isn't necessarily true. Further, there's parts of the code that relies on "impure" state via the "current date" (which will change based on when you run it), so setting a specific month in the test won't work. As such, this test makes the calculation explicit and uses the number of days in the current month. --- frontend/src/hooks/useTrafficData.test.ts | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/frontend/src/hooks/useTrafficData.test.ts b/frontend/src/hooks/useTrafficData.test.ts index 4a108e2db7ef..1ea416e39e29 100644 --- a/frontend/src/hooks/useTrafficData.test.ts +++ b/frontend/src/hooks/useTrafficData.test.ts @@ -1,3 +1,4 @@ +import { getDaysInMonth } from 'date-fns'; import { toSelectablePeriod, calculateOverageCost, @@ -122,18 +123,22 @@ describe('traffic overage calculation', () => { const now = new Date(); const period = toSelectablePeriod(now); const testNow = new Date(now.getFullYear(), now.getMonth(), 5); + const includedTraffic = 53_000_000; + const trafficUnitSize = 500_000; + const trafficUnitCost = 10; const result = calculateEstimatedMonthlyCost( period.key, testData, - 53_000_000, + includedTraffic, testNow, - 10, - 500_000, + trafficUnitCost, + trafficUnitSize, ); - // 22_500_000 * 3 * 30 = 2_025_000_000 total usage - // 2_025_000_000 - 53_000_000 = 1_972_000_000 overage - // 1_972_000_000 / 500_000 = 3_944 overage units - // 3_944 * 10 = 39_440 - expect(result).toBeGreaterThanOrEqual(39_440); + + const totalExpectedUsage = 22_500_000 * 3 * getDaysInMonth(now); + const overage = totalExpectedUsage - includedTraffic; + const overageUnits = Math.floor(overage / trafficUnitSize); + const total = overageUnits * trafficUnitCost; + expect(result).toBe(total); }); });