Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

test: adapt test scheduler to use `node-cron`

Wesley Matosb6294a173e89
diff --git a/screenpipe-js/tests/scheduler.test.ts b/screenpipe-js/tests/scheduler.test.ts
index 368281c5c..d0884c91a 100644
--- a/screenpipe-js/tests/scheduler.test.ts
+++ b/screenpipe-js/tests/scheduler.test.ts
@@ -1,127 +1,114 @@
-import { assertEquals } from "jsr:@std/assert";
-import { assertSpyCall, spy } from "jsr:@std/testing/mock";
+import {
+ assertSpyCall,
+ assertSpyCallArgs,
+ assertSpyCalls,
+ type MethodSpy,
+ spy,
+} from "jsr:@std/testing/mock";
import { pipe } from "../main.ts";
-
-Deno.test("Scheduler - task execution", async () => {
- const scheduler = pipe.scheduler;
- const mockTask = spy(() => Promise.resolve());
-
- scheduler.task("testTask").every("1 minute").do(mockTask);
-
- // Mock the Date object to control time
- const originalDate = Date;
- const mockDate = new Date("2023-01-01T00:00:00Z");
- // @ts-ignore: Overriding Date for testing purposes
- Date = class extends Date {
- constructor() {
- super();
- return mockDate;
- }
- static override now() {
- return mockDate.getTime();
- }
- };
-
- // Start the scheduler
- const schedulerPromise = scheduler.start();
-
- // Advance time by 1 minute and wait a bit longer
- await new Promise((resolve) => setTimeout(resolve, 100));
- mockDate.setMinutes(mockDate.getMinutes() + 1);
- await new Promise((resolve) => setTimeout(resolve, 100)); // Add this line
-
- // Stop the scheduler after a longer delay
- setTimeout(() => {
- scheduler.stop();
- }, 500); // Increase this delay
-
- await schedulerPromise;
-
- // Restore the original Date object
- Date = originalDate;
-
- // Assert that the task was called
- assertSpyCall(mockTask, 0);
-});
-
-Deno.test("Scheduler - multiple tasks", async () => {
- const scheduler = pipe.scheduler;
- const mockTask1 = spy(() => Promise.resolve());
- const mockTask2 = spy(() => Promise.resolve());
-
- scheduler.task("task1").every("1 minute").do(mockTask1);
-
- scheduler.task("task2").every("2 minutes").do(mockTask2);
-
- // Mock the Date object
- const originalDate = Date;
- const mockDate = new Date("2023-01-01T00:00:00Z");
- // @ts-ignore: Overriding Date for testing purposes
- Date = class extends Date {
- constructor() {
- super();
- return mockDate;
- }
- static override now() {
- return mockDate.getTime();
- }
- };
-
- // Start the scheduler
- const schedulerPromise = scheduler.start();
-
- // Advance time by 2 minutes and wait a bit longer
- await new Promise((resolve) => setTimeout(resolve, 100));
- mockDate.setMinutes(mockDate.getMinutes() + 2);
- await new Promise((resolve) => setTimeout(resolve, 100)); // Add this line
-
- // Stop the scheduler after a longer delay
- setTimeout(() => {
- scheduler.stop();
- }, 500); // Increase this delay
-
- await schedulerPromise;
-
- // Restore the original Date object
- Date = originalDate;
-
- // Assert that tasks were called at least the expected number of times
- assertEquals(mockTask1.calls.length >= 2, true);
- assertEquals(mockTask2.calls.length >= 1, true);
-});
-
-Deno.test("Scheduler - state persistence", async () => {
- const tempDir = await Deno.makeTempDir();
- const originalEnv = Deno.env.get("SCREENPIPE_DIR");
- Deno.env.set("SCREENPIPE_DIR", tempDir);
-
- const scheduler = pipe.scheduler;
- const mockTask = spy(() => Promise.resolve());
-
- scheduler.task("persistentTask").every("1 minute").do(mockTask);
-
- // Mock Date as before
- // ...
-
- // Run scheduler for a short time
- const schedulerPromise = scheduler.start();
- await new Promise((resolve) => setTimeout(resolve, 200));
- scheduler.stop();
- await schedulerPromise;
-
- // Create a new scheduler instance (simulating process restart)
- const newScheduler = pipe.scheduler;
- newScheduler.task("persistentTask").every("1 minute").do(mockTask);
-
- // Verify that the task's next run time was loaded from the persistent state
- const task = newScheduler["tasks"][0];
- assertEquals(task.getNextRunTime().getTime() > Date.now(), true);
-
- // Clean up
- await Deno.remove(tempDir, { recursive: true });
- if (originalEnv) {
- Deno.env.set("SCREENPIPE_DIR", originalEnv);
- } else {
- Deno.env.delete("SCREENPIPE_DIR");
- }
+import { afterEach, beforeEach, describe, it } from "jsr:@std/testing/bdd";
+// @ts-types="npm:@types/node-cron"
+import cron from "npm:node-cron";
+import { retry } from "jsr:@std/async/retry";
+import { assertGreaterOrEqual, assertLessOrEqual } from "jsr:@std/assert@^1.0.6";
+
+describe("Scheduler", () => {
+ let cronSpy: MethodSpy<
+ typeof cron,
+ Parameters<typeof cron.schedule>,
+ ReturnType<typeof cron.schedule>
+ >;
+
+ beforeEach(async () => {
+ cronSpy = await spy(cron, "schedule");
+ });
+
+ afterEach(() => {
+ cronSpy.restore();
+ pipe.scheduler.stop();
+ });
+
+ it("Scheduler - task execution", async () => {
+ const scheduler = pipe.scheduler;
+ const mockTask = spy(() => Promise.resolve());
+
+ scheduler.task("testTask").every("1 second").do(mockTask);
+
+ // Validate the cron job was not scheduled yet
+ assertSpyCalls(cronSpy, 0);
+
+ // Register the routes on node-cron
+ scheduler.start();
+
+ // Validate the cron jobs were scheduled
+ assertSpyCall(cronSpy, 0);
+ assertSpyCallArgs(cronSpy, 0, ["*/1 * * * * *", mockTask, {
+ name: "testTask",
+ }]);
+
+ // retry until the task runs
+ await retry(() => {
+ assertSpyCalls(mockTask, 1);
+ }, {
+ maxAttempts: 10,
+ maxTimeout: 1000,
+ minTimeout: 200,
+ });
+ });
+
+ it("multiple tasks", async () => {
+ const scheduler = pipe.scheduler;
+ const mockTask1 = spy(() => Promise.resolve());
+ const mockTask2 = spy(() => Promise.resolve());
+
+ scheduler.task("task1").every("1 second").do(mockTask1);
+
+ scheduler.task("task2").every("2 seconds").do(mockTask2);
+
+ // Validate the cron jobs were not scheduled yet
+ assertSpyCalls(cronSpy, 0);
+
+ // Register the routes on node-cron
+ scheduler.start();
+
+ // Validate the cron jobs were scheduled
+ assertSpyCalls(cronSpy, 2);
+ assertSpyCallArgs(cronSpy, 0, ["*/1 * * * * *", mockTask1, {
+ name: "task1",
+ }]);
+ assertSpyCallArgs(cronSpy, 1, ["*/2 * * * * *", mockTask2, {
+ name: "task2",
+ }]);
+
+ // IMPORTANT: The assertions as below are not deterministic, thus we need to retry
+ // Retrying is an optimized way of `await setTimeout(xTime)` until the condition is met
+ // Avoid checking literal values, e.g., mockTask1.calls.length === 1 && mockTask2.calls.length === 0
+ // Instead, use `assertGreaterOrEqual` or `assertLessOrEqual` to make the test more resilient
+ // and avoid flakiness
+
+ // retry until the first task runs
+ // and ensure the second was not called yet
+ await retry(() => {
+ // 1 sec job was called at least once
+ assertGreaterOrEqual(mockTask1.calls.length, 1);
+ // 2 sec job was called half the times of the 1 sec job (or less)
+ assertLessOrEqual(mockTask2.calls.length, Math.ceil(mockTask1.calls.length / 2));
+ }, {
+ maxAttempts: 10,
+ maxTimeout: 1000,
+ minTimeout: 100,
+ });
+
+ // retry a bunch of times until the second task is called
+ await retry(() => {
+ // 2 sec job was called at least once
+ assertGreaterOrEqual(mockTask2.calls.length, 1);
+ // 1 sec job was called at least twice the times of the 2 sec job
+ assertGreaterOrEqual(mockTask1.calls.length, mockTask2.calls.length * 2);
+ }, {
+ maxAttempts: 10,
+ maxTimeout: 1000,
+ minTimeout: 100,
+ });
+ });
});