tol*_*gap 3 unit-testing clojure clojurescript om
我仍处于 Cljs 和 Om 的学习阶段。我正在研究编写组件测试。一些组件cljs-http调用了我创建的 API。测试时,我不希望这些 API 调用实际发送请求,因此我正在研究模拟请求并返回一个装置。这是我拥有的示例组件:
(defn async-component [data owner]
(reify
IWillMount
(will-mount [_]
(let [resp (go ((<! (async-call "/") :body))]
(om/update! data [:objects] resp)))
IRender
(render [_]
[:ul
(om/build-all item-component data)])))
(defn async-call [path]
(http/get path {:keywordize-keys true}))
Run Code Online (Sandbox Code Playgroud)
请不要介意代码实际上在语法上是否正确,我只是展示了它的要点。
我现在想要做的是测试这个async-component和 API 调用,看看它是否会呈现我模拟请求的夹具。这是怎么做的?我知道cljs.test有async用于测试异步代码的块,但所有示例都显示它测试只有 a 的实际代码块go,而不是在更大的上下文中。
这是您可以使用模拟来测试您的组件的一种方法:
(deftest test-async-component
(cljs.test/async done
(with-redefs
[async-call (fn [path]
(let [mock-ch (async/chan 1)
fixture-data {:body {:fixture-with path :and "foobar"}})]
(async/put! mock-ch fixture-data)
mock-ch)]
; At this point we successfully mocked out our data source (the API call)
; the only task that remains is to render our Om component into DOM and inspect it.
; As this task requires utility fns I will reuse the ones in this blog post:
; http://lab.brightnorth.co.uk/2015/01/27/unit-and-browser-testing-om-clojurescript-applications/
(let [c (new-container!)
initial-data {:objects [{:initial-object 42}]}]
; This will mount and render your component into the DOM residing in c.
(om/root async-component initial-data {:target c})
(testing "fixture data gets put into the DOM"
(is (= "foobar" (text (sel1 c :ul)))))
; You can add more tests in this manner, then finally call 'done'.
(done)))))
Run Code Online (Sandbox Code Playgroud)
上面英文代码中采取的步骤:
async-call的模拟 fn 返回一个通道(与原始通道相同的接口)预填充夹具数据。async-call在om/will-mount运行时调用,fixture-data取消chan)。| 归档时间: |
|
| 查看次数: |
609 次 |
| 最近记录: |