fix(costs): ignore a settlement answer that lands after the ledger unmounted

A read still in flight when the Costs view closed set state on the gone component; in a torn-down test environment React then failed on the missing window and the run reported an unhandled error.
This commit is contained in:
Maurice
2026-11-28 19:21:59 +01:00
parent 7e9ab58a16
commit c39f739b7f
2 changed files with 30 additions and 1 deletions
@@ -16,7 +16,7 @@ import type { CostsSettlementResponse } from './costsModel';
import { useCostsLedger } from './useCostsLedger';
import { useFreezeMissingRates } from './useFreezeMissingRates';
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-023
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-024
const fx = vi.hoisted(() => ({
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
@@ -183,6 +183,28 @@ describe('useCostsLedger: loading', () => {
expect(result.current.settlement).toEqual(SETTLEMENT);
});
it('FE-BUDGET-LEDGER-024: a settlement answer that lands after the ledger is gone changes no state', async () => {
let fail: (reason: Error) => void = () => undefined;
settlementMock().mockImplementation(
() =>
new Promise<CostsSettlementResponse>((_resolve, reject) => {
fail = reject;
})
);
const { unmount } = setup();
await waitFor(() => expect(settlementMock()).toHaveBeenCalled());
unmount();
// React reads window.event when a state update is scheduled, and a test
// environment that is already torn down has no window.
vi.stubGlobal('window', undefined);
try {
fail(new Error('gone'));
await new Promise((resolve) => setTimeout(resolve, 20));
} finally {
vi.unstubAllGlobals();
}
});
it('FE-BUDGET-LEDGER-006: hands the unconverted rows to the rate freeze, which reads the settlement again once healed', async () => {
const { result } = setup();
await waitFor(() => expect(result.current.settlement).not.toBeNull());
@@ -120,6 +120,13 @@ export function useCostsLedger({
// Only the latest read may land: an answer for the currency picked before would
// otherwise overwrite the one for the currency shown now.
const latestRead = useRef(0);
// An answer that lands after the ledger is gone has nobody to show it to.
useEffect(() => {
const reads = latestRead;
return () => {
reads.current += 1;
};
}, []);
// The browser's own figure for the display currency goes along, for the server to
// answer in it when it cannot fetch a quote itself.