Skip to content

Instantly share code, notes, and snippets.

@munk
Created December 6, 2015 00:13
Show Gist options
  • Save munk/d4c63ecf2fc734fb0673 to your computer and use it in GitHub Desktop.
Save munk/d4c63ecf2fc734fb0673 to your computer and use it in GitHub Desktop.
Testing with core.async and reagent
(ns framework
(:require [reagent.core :as reagent]))
(def isClient (not (nil? (try (.-document js/window)
(catch js/Object e nil)))))
(def rflush reagent/flush)
(defn add-test-div [name]
(let [doc js/document
body (.-body js/document)
div (.createElement doc "div")]
(.appendChild body div)
div))
(defn with-mounted-component [comp f]
(when isClient
(let [div (add-test-div "_testreagent")]
(let [comp (reagent/render-component comp div #(f comp div))]
(reagent/unmount-component-at-node div)
(reagent/flush)
(.removeChild (.-body js/document) div)))))
(ns test
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [framework :refer [with-mounted-component]]
[cljs-http.client :as http]
[cljs.core.async :refer [<! >! chan]]
[cljs.test]))
(def state (atom {:page :test}))
(defn post-data [d]
(go
(let [result (->> {:form-params {:data @d}}
(http/post "/api/dostuff")
(<!))
{status :status body :body} result]
(case status
401 (swap! state assoc :page :success)
200 (swap! state assoc :page :failure)))))
(defn submit [id f]
[:div
[:button {:on-click on-click :id id}
id]])
(defn form [f]
(let [input (atom "data")]
[:div
[submit "DoStuff"
(fn [] (f input))]]))
(defn fake-post-success [& _]
(let [ch (chan)
response {:status 200 :body "it worked!"}]
(go (>! ch response)
ch)))
(deftest form-test
(with-redefs [http/post fake-post-success]
(with-mounted-component (form post-data)
(fn [c div]
(async done
(.click (.getElementById js/document "DoStuff"))
(fn []
(is (= (:page @state) :success))
(done)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment