import test from 'node:test'; import assert from 'node:assert/strict'; import { loadBackground, hasBackground, RETRIES, RETRY_WAIT } from '../src/engine/render.js'; // Un Image finto: fallisce le prime `fails` volte per ogni indirizzo, e conta le richieste. function fakeImage(fails) { const asked = new Map(); globalThis.Image = class { set src(v) { const n = (asked.get(v) ?? 0) + 1; asked.set(v, n); queueMicrotask(() => (n <= fails ? this.onerror() : this.onload())); } }; return asked; } test('uno sfondo che non arriva si riprova dopo un po\', non a ogni fotogramma, e alla fine arriva', async () => { const asked = fakeImage(2), src = 'x/rete-ballerina.png'; try { assert.equal(await loadBackground(src), false); assert.equal(await loadBackground(src), false, 'subito dopo non si riprova'); assert.equal(asked.get(src), 1); assert.equal(await loadBackground(src, Date.now() + RETRY_WAIT + 1), false, 'dopo l\'attesa si riprova'); assert.equal(asked.get(src), 2); assert.equal(await loadBackground(src, Date.now() + RETRY_WAIT + 1), false, 'la seconda attesa è più lunga'); assert.equal(asked.get(src), 2); assert.equal(await loadBackground(src, Date.now() + 2 * RETRY_WAIT + 1), true); assert.ok(hasBackground(src)); } finally { delete globalThis.Image; } }); test('uno sfondo che non c\'è proprio si lascia stare dopo pochi tentativi', async () => { const asked = fakeImage(Infinity), src = 'x/non-esiste.png', later = () => Date.now() + 3600e3; try { for (let i = 0; i < 10; i++) await loadBackground(src, later()); assert.equal(asked.get(src), RETRIES + 1); } finally { delete globalThis.Image; } });