Eric Bower
·
2025-06-06
timer.test.ts
1import { clearTimers, put, run, sleep, spawn, timer } from "../index.js";
2import { expect, test } from "../test.js";
3
4test("should call thunk at most once every timer", async () => {
5 expect.assertions(1);
6 let called = 0;
7 await run(function* () {
8 yield* spawn(function* () {
9 yield* timer(10)("ACTION", function* () {
10 called += 1;
11 });
12 });
13 yield* put({ type: "ACTION", payload: { key: "my-key" } });
14 yield* sleep(1);
15 yield* put({ type: "ACTION", payload: { key: "my-key" } });
16 yield* sleep(20);
17 yield* put({ type: "ACTION", payload: { key: "my-key" } });
18 yield* sleep(50);
19 });
20 expect(called).toBe(2);
21});
22
23test("should let user cancel timer", async () => {
24 expect.assertions(1);
25 let called = 0;
26 await run(function* () {
27 yield* spawn(function* () {
28 yield* timer(10_000)("ACTION", function* () {
29 called += 1;
30 });
31 });
32 yield* put({ type: "ACTION", payload: { key: "my-key" } });
33 yield* sleep(1);
34 yield* put(clearTimers(["my-key"]));
35 yield* put({ type: "ACTION", payload: { key: "my-key" } });
36 });
37 expect(called).toBe(2);
38});
39
40test("should let user cancel timer with action obj", async () => {
41 expect.assertions(1);
42 let called = 0;
43 await run(function* () {
44 yield* spawn(function* () {
45 yield* timer(10_000)("ACTION", function* () {
46 called += 1;
47 });
48 });
49 const action = { type: "ACTION", payload: { key: "my-key" } };
50 yield* put(action);
51 yield* sleep(1);
52 yield* put(clearTimers(action));
53 yield* put(action);
54 });
55 expect(called).toBe(2);
56});
57
58test("should let user cancel timer with wildcard", async () => {
59 expect.assertions(1);
60 let called = 0;
61 await run(function* () {
62 yield* spawn(function* () {
63 yield* timer(10_000)("ACTION", function* () {
64 called += 1;
65 });
66 });
67 yield* spawn(function* () {
68 yield* timer(10_000)("WOW", function* () {
69 called += 1;
70 });
71 });
72 yield* put({ type: "ACTION", payload: { key: "my-key" } });
73 yield* put({ type: "WOW", payload: { key: "my-key" } });
74 yield* sleep(1);
75 yield* put(clearTimers(["*"]));
76 yield* put({ type: "ACTION", payload: { key: "my-key" } });
77 yield* put({ type: "WOW", payload: { key: "my-key" } });
78 });
79 expect(called).toBe(4);
80});