repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

starfx / test
Eric Bower · 23 Feb 24

timer.test.ts

 1import { describe, expect, it } from "../test.ts";
 2import { clearTimers, put, run, sleep, spawn, timer } from "../mod.ts";
 3
 4const tests = describe("timer()");
 5
 6it(tests, "should call thunk at most once every timer", async () => {
 7  let called = 0;
 8  await run(function* () {
 9    yield* spawn(function* () {
10      yield* timer(10)("ACTION", function* () {
11        called += 1;
12      });
13    });
14    yield* put({ type: "ACTION", payload: { key: "my-key" } });
15    yield* sleep(1);
16    yield* put({ type: "ACTION", payload: { key: "my-key" } });
17    yield* sleep(20);
18    yield* put({ type: "ACTION", payload: { key: "my-key" } });
19    yield* sleep(50);
20  });
21  expect(called).toBe(2);
22});
23
24it(tests, "should let user cancel timer", async () => {
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
40it(tests, "should let user cancel timer with action obj", async () => {
41  let called = 0;
42  await run(function* () {
43    yield* spawn(function* () {
44      yield* timer(10_000)("ACTION", function* () {
45        called += 1;
46      });
47    });
48    const action = { type: "ACTION", payload: { key: "my-key" } };
49    yield* put(action);
50    yield* sleep(1);
51    yield* put(clearTimers(action));
52    yield* put(action);
53  });
54  expect(called).toBe(2);
55});
56
57it(tests, "should let user cancel timer with wildcard", async () => {
58  let called = 0;
59  await run(function* () {
60    yield* spawn(function* () {
61      yield* timer(10_000)("ACTION", function* () {
62        called += 1;
63      });
64    });
65    yield* spawn(function* () {
66      yield* timer(10_000)("WOW", function* () {
67        called += 1;
68      });
69    });
70    yield* put({ type: "ACTION", payload: { key: "my-key" } });
71    yield* put({ type: "WOW", payload: { key: "my-key" } });
72    yield* sleep(1);
73    yield* put(clearTimers(["*"]));
74    yield* put({ type: "ACTION", payload: { key: "my-key" } });
75    yield* put({ type: "WOW", payload: { key: "my-key" } });
76  });
77  expect(called).toBe(4);
78});