Skip to content

Instantly share code, notes, and snippets.

@oliyh
Last active August 2, 2016 12:05
Show Gist options
  • Save oliyh/ca4bf0d090b6c7f15ca607e07bc61f9f to your computer and use it in GitHub Desktop.
Save oliyh/ca4bf0d090b6c7f15ca607e07bc61f9f to your computer and use it in GitHub Desktop.
Testing re-frame subscriptions with synchronous dispatch
(ns model
(:require [re-frame.core :as re-frame]))
(re-frame/def-event ::toggle-sort-direction []
(fn [db _]
(update db :sort-asc? not)))
(re-frame/def-sub ::sort-asc?
(fn [db _]
(get db :sort-asc? true)))
(re-frame/def-event ::sort-by []
(fn [db [_ [sort-key]]]
(when (= sort-key (:sort-by db))
(re-frame/dispatch [::toggle-sort-direction]))
(assoc db :sort-by sort-key)))
(re-frame/def-sub ::sort-key
(fn [db _]
(get db :sort-by :name)))
(re-frame/def-sub ::sorted-data
(fn [_]
[(re-frame/subscribe [::sort-key])
(re-frame/subscribe [::sort-asc?])])
(fn [[sort-key sort-asc?] _]
(->> [{:name "James" :age 30}
{:name "Fiona" :age 24}
{:name "Anna" :age 28}]
(sort-by sort-key)
((if sort-asc? identity reverse)))))
(ns model-test
(:require [cljs.test :as test]
[re-frame.core :as re-frame]
[model :as model]))
(test/deftest can-sort-test
(let [sorted-data (re-frame/subscribe ::model/sorted-data)]
(test/testing "sorts by name by default"
(test/is (= [{:name "Anna" :age 28}
{:name "Fiona" :age 24}
{:name "James" :age 30}]
@sorted-data)))
(test/testing "can sort by age"
(re-frame/dispatch [::model/sort-by :age])
;; want to wait for all events to be processed before making the next assertion
(test/is (= [{:name "Fiona" :age 24}
{:name "Anna" :age 28}
{:name "James" :age 30}])))
(test/testing "can toggle sort direction"
(re-frame/dispatch [::model/sort-by :age])
;; want to wait for all events to be processed before making the next assertion
(test/is (= [{:name "James" :age 30}
{:name "Anna" :age 28}
{:name "Fiona" :age 24}])))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment