/ tests / utils / cpu-monitor-supplement.test.js
cpu-monitor-supplement.test.js
 1  /**
 2   * CPU Monitor Supplement — Hit computeUsage and setInterval callback (lines 19-44)
 3   *
 4   * The existing tests stop the monitor before the 200ms interval fires.
 5   * These tests wait for the interval to fire, executing:
 6   * - Lines 19-35: computeUsage() — CPU tick delta calculation
 7   * - Lines 42-44: setInterval callback body — snapshot update + usage compute
 8   */
 9  
10  import { test, describe, after } from 'node:test';
11  import assert from 'node:assert/strict';
12  import { getCurrentCpuUsage, stopCpuMonitor } from '../../src/utils/cpu-monitor.js';
13  
14  after(() => {
15    stopCpuMonitor();
16  });
17  
18  describe('cpu-monitor-supplement - setInterval callback coverage', () => {
19    test('getCurrentCpuUsage reflects real CPU usage after 250ms (fires the setInterval callback)', async () => {
20      // Restart fresh
21      stopCpuMonitor();
22      const initial = getCurrentCpuUsage(); // starts monitor, currentCpuUsage = 0
23  
24      // Wait for the 200ms interval to fire (execute computeUsage + update lastSnapshot)
25      await new Promise(resolve => setTimeout(resolve, 250));
26  
27      const usage = getCurrentCpuUsage();
28      assert.ok(typeof usage === 'number', 'should return a number');
29      assert.ok(usage >= 0, `CPU usage should be >= 0, got ${usage}`);
30      assert.ok(usage <= 1, `CPU usage should be <= 1, got ${usage}`);
31      // After 250ms, the interval has fired: computeUsage() ran, currentCpuUsage is updated
32      // initial is 0.0, usage may still be 0 if CPU is idle, but the callback executed
33    });
34  
35    test('computeUsage handles CPU tick deltas correctly over multiple intervals', async () => {
36      stopCpuMonitor();
37      getCurrentCpuUsage(); // restart monitor
38  
39      // Let 3 intervals fire (3 × 200ms = 600ms)
40      await new Promise(resolve => setTimeout(resolve, 650));
41  
42      const usage = getCurrentCpuUsage();
43      assert.ok(typeof usage === 'number', 'should return a number after multiple intervals');
44      assert.ok(usage >= 0 && usage <= 1, `usage should be in [0, 1], got ${usage}`);
45    });
46  
47    test('monitor produces stable readings (computeUsage returns 0 when no tick delta)', async () => {
48      stopCpuMonitor();
49      getCurrentCpuUsage(); // start fresh
50  
51      // Wait for interval to fire
52      await new Promise(resolve => setTimeout(resolve, 250));
53  
54      // Multiple rapid reads should all return same value (computeUsage cached until next interval)
55      const r1 = getCurrentCpuUsage();
56      const r2 = getCurrentCpuUsage();
57      assert.equal(r1, r2, 'consecutive reads should return same cached value');
58      assert.ok(r1 >= 0 && r1 <= 1, 'reading should be in valid range');
59    });
60  });