Skip to content

Instantly share code, notes, and snippets.

@cdbkr
Last active August 13, 2024 18:27
Show Gist options
  • Save cdbkr/f195d7fbb600fae9655f37e7b2b4813e to your computer and use it in GitHub Desktop.
Save cdbkr/f195d7fbb600fae9655f37e7b2b4813e to your computer and use it in GitHub Desktop.
React-testing-library and Re-frame clojurescript app
(ns demo.core-test
(:require [cljs.test :refer [deftest
testing
is
use-fixtures]]
[clojure.string :refer [lower-case]]
[demo.components :refer [title-component
counter-component]]
[reagent.core :as r]
["react-testing-library" :as rtl]))
(use-fixtures :each
{:after rtl/cleanup})
;; Idea from https://github.com/reagent-project/reagent/blob/master/test/reagenttest/utils.cljs
(defn with-mounted-component [comp f]
(let [mounted-component (rtl/render (r/as-element comp))]
(try
(f mounted-component)
(finally
(.unmount mounted-component)
(r/flush)))))
(defn click-element [el]
(.click rtl/fireEvent el)
(r/flush))
(deftest test-title
(testing "A provided title should be enclosed in a h1"
(with-mounted-component
[title-component "hello"]
(fn [component]
(is
(= "h1"
(-> component
(.getByText "hello")
(.-tagName)
lower-case))))))
(testing "A title saying 'hello' is shown to the user"
(with-mounted-component
[title-component "hello"]
(fn [component]
(is
(= "hello"
(-> component
(.getByText "hello")
(.-innerHTML))))))))
(deftest test-stateful-component
(testing "A counter should track clicks"
(with-mounted-component
[counter-component {:text "increase"}]
(fn [component]
(is
(= "Counter: 0"
(->> (.getByText component #"Counter:")
(.-innerHTML))))
(click-element (.getByText component "increase"))
(is
(= "Counter: 1"
(->> (.getByText component #"Counter:")
(.-innerHTML))))))))
@emmanuj
Copy link

emmanuj commented Jan 9, 2021

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment