/
ajax_test_util.cljs
63 lines (55 loc) · 2.36 KB
/
ajax_test_util.cljs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
(ns reacl-c-basics.ajax-test-util
(:require [reacl-c.core :as c :include-macros true]
[reacl-c-basics.ajax :as ajax]
[reacl-c.test-util.core :as tu]))
(defn request-subscribe-effect?
"Returns if the given effect action performs the subscription to the result of the given request."
[eff & [request]]
(if request
;; with a concrete requests
(tu/subscribe-effect? eff (ajax/execute request))
;; or generally, a request should be at a certain position of the subscription-effect args
(and (tu/subscribe-effect? eff)
(let [[req] (tu/subscribe-effect-args eff)]
(ajax/request? req)))))
(defn request-unsubscribe-effect?
"Returns if the given effect action performs the unsubscription from the result of the given request."
[eff]
(and (tu/unsubscribe-effect? eff)
(let [[req] (tu/unsubscribe-effect-args eff)]
(ajax/request? req))))
(defn request-subscribe-effect-request
[eff]
;; Note: only for the subscription effect (not the unsubscription)
(assert (request-subscribe-effect? eff))
(first (tu/subscribe-effect-args eff)))
(defn request-unsubscribe-effect-request
[eff]
;; Note: only for the subscription effect (not the unsubscription)
(assert (request-unsubscribe-effect? eff))
(first (tu/unsubscribe-effect-args eff)))
(defn requests-emulator
"Returns an effect reducer, that calls f for all ajax requests that
are subscribed to in a test environment, and if f returns a
response, then makes it an action emitted from the corresponding
subscription item. Otherwise it is passed on."
[f]
(fn [env eff]
(cond
(request-subscribe-effect? eff)
(let [req (request-subscribe-effect-request eff)]
(if-let [resp (f req)]
;; TODO: merge-returned should be in core or tu
(reacl-c.base/merge-returned (tu/subscription-start-return env eff)
(tu/subscription-result-return env eff resp))
(c/return :action eff)))
(request-unsubscribe-effect? eff)
(let [req (request-unsubscribe-effect-request eff)]
;; is it one of the requests we emulate here? Then drop
;; it (it's a noop anyway - no stop! fn passed to
;; subscription-start-return)
(if (some? (f req))
(c/return)
(c/return :action eff)))
:else
(c/return :action eff))))