|
| 1 | +import { |
| 2 | + assertEquals, |
| 3 | + assert, |
| 4 | +} from "https://deno.land/[email protected]/testing/asserts.ts"; |
| 5 | +import { IdleModule } from "../../../src/modules/idle.js"; |
| 6 | + |
| 7 | +// Mock requestIdleCallback and cancelIdleCallback |
| 8 | +globalThis.requestIdleCallback = (callback) => { |
| 9 | + const id = setTimeout(() => { |
| 10 | + callback({ timeRemaining: () => 50, didTimeout: false }); |
| 11 | + clearTimeout(id); |
| 12 | + }, 0); |
| 13 | + return id; |
| 14 | +}; |
| 15 | + |
| 16 | +globalThis.cancelIdleCallback = (id) => { |
| 17 | + clearTimeout(id); |
| 18 | +}; |
| 19 | + |
| 20 | +Deno.test("IdleWorker should execute tasks when idle", async () => { |
| 21 | + let taskExecuted = false; |
| 22 | + const task = () => { taskExecuted = true; }; |
| 23 | + |
| 24 | + IdleModule.perform({ tasks: [task] }); |
| 25 | + |
| 26 | + // Simulate idle period |
| 27 | + await new Promise(resolve => { |
| 28 | + const id = requestIdleCallback(() => { |
| 29 | + assert(taskExecuted, "Task should have been executed during idle period"); |
| 30 | + cancelIdleCallback(id); // Clear the timeout to prevent leaks |
| 31 | + resolve(); |
| 32 | + }); |
| 33 | + }); |
| 34 | +}); |
| 35 | + |
| 36 | +Deno.test("IdleWorker should execute multiple tasks when idle", async () => { |
| 37 | + let task1Executed = false; |
| 38 | + let task2Executed = false; |
| 39 | + const task1 = () => { task1Executed = true; }; |
| 40 | + const task2 = () => { task2Executed = true; }; |
| 41 | + |
| 42 | + IdleModule.perform({ tasks: [task1, task2] }); |
| 43 | + |
| 44 | + // Simulate idle period |
| 45 | + await new Promise(resolve => { |
| 46 | + const id = requestIdleCallback((deadline) => { |
| 47 | + assert(task1Executed, "Task 1 should have been executed during idle period"); |
| 48 | + assert(task2Executed, "Task 2 should have been executed during idle period"); |
| 49 | + cancelIdleCallback(id); // Clear the timeout to prevent leaks |
| 50 | + resolve(); |
| 51 | + }); |
| 52 | + }); |
| 53 | +}); |
| 54 | + |
| 55 | +Deno.test("IdleWorker should handle empty task list", async () => { |
| 56 | + IdleModule.perform({ tasks: [] }); |
| 57 | + |
| 58 | + // Simulate idle period |
| 59 | + await new Promise(resolve => { |
| 60 | + const id = requestIdleCallback((deadline) => { |
| 61 | + assertEquals(globalThis.idleWorker.count, 0, "Queue should be empty"); |
| 62 | + cancelIdleCallback(id); // Clear the timeout to prevent leaks |
| 63 | + resolve(); |
| 64 | + }); |
| 65 | + }); |
| 66 | +}); |
| 67 | + |
0 commit comments