-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_mocks.cljc
96 lines (87 loc) · 2.88 KB
/
web_mocks.cljc
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
(ns dgknght.app-lib.web-mocks
#?(:cljs (:require-macros [dgknght.app-lib.web-mocks.cljs]))
(:require [lambdaisland.uri :refer [query-string->map]]
[dgknght.app-lib.web-mocks.matching :refer [match?]]
[dgknght.app-lib.web-mocks.impl :as impl]
#?(:cljs [cljs.core.async :as a])
#?(:clj [clojure.test :as test])
#?(:cljs [goog.string :as gstr])))
#?(:cljs
(defn- format
[f & args]
(apply gstr/format f args)))
(defn parse-query-string
[{:keys [query-string] :as m}]
(if query-string
(assoc m :query-params (query-string->map query-string))
m))
(defn- call-matching-mock
[req mocks]
(or (->> mocks
(filter #(match? req (first %)))
(map #((second %) req))
first)
(println "Unable to match the request: " (prn-str req))
(println "Mocks " (prn-str mocks))))
(defn request-handler
[calls mocks]
(fn [req]
(swap! calls conj req)
#?(:clj (call-matching-mock req mocks)
:cljs (let [ch (:channel req)
res (call-matching-mock req mocks)]
(when res
(a/put! ch res))
(a/close! ch)
ch))))
(defmacro with-web-mocks
[bindings mocks-map & body]
`(let [f# (fn* [~(first bindings)] ~@body)
calls# (atom [])]
(with-redefs [http/request (comp (request-handler calls# ~mocks-map)
parse-query-string)]
(f# calls#))))
#?(:clj
(defmethod test/assert-expr 'called?
[msg form]
`(test/do-report
~(impl/called? msg form)))
:cljs
(when (exists? js/cljs.test$macros)
(defmethod js/cljs.test$macros.assert_expr 'dgknght.app-lib.web-mocks/called?
[_env msg form]
`(test/do-report
~(impl/called? msg form)))))
#?(:clj
(defmethod test/assert-expr 'not-called?
[msg form]
`(test/do-report
~(impl/not-called? msg form)))
:cljs
(when (exists? js/cljs.test$macros)
(defmethod js/cljs.test$macros.assert_expr 'dgknght.app-lib.web-mocks/not-called?
[_env msg form]
`(test/do-report
~(impl/not-called? msg form)))))
#?(:clj
(defmethod test/assert-expr 'matches-headers?
[msg form]
`(test/do-report
~(impl/matches-headers? msg form)))
:cljs
(when (exists? js/cljs.test$macros)
(defmethod js/cljs.test$macros.assert_expr 'dgknght.app-lib.web-mocks/matches-headers?
[_env msg form]
`(test/do-report
~(impl/matches-headers? msg form)))))
#?(:clj
(defmethod test/assert-expr 'called-with-headers?
[msg form]
`(test/do-report
~(impl/called-with-headers? msg form)))
:cljs
(when (exists? js/cljs.test$macros)
(defmethod js/cljs.test$macros.assert_expr 'dgknght.app-lib.web-mocks/called-with-headers?
[_env msg form]
`(test/do-report
~(impl/called-with-headers? msg form)))))