Eric Bower
·
2025-06-06
take.test.ts
1import type { AnyAction } from "../index.js";
2import { put, sleep, spawn, take } from "../index.js";
3import { createStore } from "../store/index.js";
4import { expect, test } from "../test.js";
5
6test("a put should complete before more `take` are added and then consumed automatically", async () => {
7 const actual: AnyAction[] = [];
8
9 function* channelFn() {
10 yield* sleep(10);
11 yield* put({ type: "action-1", payload: 1 });
12 yield* put({ type: "action-1", payload: 2 });
13 }
14
15 function* root() {
16 yield* spawn(channelFn);
17
18 actual.push(yield* take("action-1"));
19 actual.push(yield* take("action-1"));
20 }
21
22 const store = createStore({ initialState: {} });
23 await store.run(root);
24
25 expect(actual).toEqual([
26 { type: "action-1", payload: 1 },
27 { type: "action-1", payload: 2 },
28 ]);
29});
30
31test("take from default channel", async () => {
32 expect.assertions(1);
33 function* channelFn() {
34 yield* sleep(10);
35 yield* put({ type: "action-*" });
36 yield* put({ type: "action-1" });
37 yield* put({ type: "action-2" });
38 yield* put({ type: "unnoticeable-action" });
39 yield* put({
40 type: "",
41 payload: {
42 isAction: true,
43 },
44 });
45 yield* put({
46 type: "",
47 payload: {
48 isMixedWithPredicate: true,
49 },
50 });
51 yield* put({
52 type: "action-3",
53 });
54 }
55
56 const actual: AnyAction[] = [];
57 function* genFn() {
58 yield* spawn(channelFn);
59
60 try {
61 actual.push(yield* take("*")); // take all actions
62 actual.push(yield* take("action-1")); // take only actions of type 'action-1'
63 actual.push(yield* take(["action-2", "action-2222"])); // take either type
64 actual.push(yield* take((a: AnyAction) => a.payload?.isAction)); // take if match predicate
65 actual.push(
66 yield* take([
67 "action-3",
68 (a: AnyAction) => a.payload?.isMixedWithPredicate,
69 ]),
70 ); // take if match any from the mixed array
71 actual.push(
72 yield* take([
73 "action-3",
74 (a: AnyAction) => a.payload?.isMixedWithPredicate,
75 ]),
76 ); // take if match any from the mixed array
77 } finally {
78 actual.push({ type: "auto ended" });
79 }
80 }
81
82 const store = createStore({ initialState: {} });
83 await store.run(genFn);
84
85 const expected = [
86 {
87 type: "action-*",
88 },
89 {
90 type: "action-1",
91 },
92 {
93 type: "action-2",
94 },
95 {
96 type: "",
97 payload: {
98 isAction: true,
99 },
100 },
101 {
102 type: "",
103 payload: {
104 isMixedWithPredicate: true,
105 },
106 },
107 {
108 type: "action-3",
109 },
110 { type: "auto ended" },
111 ];
112 expect(actual).toEqual(expected);
113});