Clojurescript/Reagent Unit testing component - sim

2019-08-20 22:41发布

问题:

For a component where I have a textbox, I need to be able to change the text in it from the test:

(defn choose-city-component []
  (let [inner-state (r/atom {:text ""})]
    (fn []
      [:div
       [:input#txt_city {
            :type "text"
            :value (@inner-state :text)
             :on-change #(swap! inner-state assoc :text (-> % .-target .-value))...

In the test I render it on the screen:

(deftest choose-city-component-test-out
  ;;GIVEN render component in test
  (let [comp (r/render-component [w/choose-city-component]
                             (. js/document (getElementById "test")))]
    ;;WHEN changing the city....

Now using jQuery trigger I'm trying to simulate an onChange on the text:

We tried

(.change ($ :#txt_city) {"target" {"value" "Paris"}})

and

(.trigger ($ :#txt_city) "change" {"target" {"value" "Paris"}}))

But it doesn't work...

回答1:

I don't know jQuery very well, but shouldn't your code be more like (js/$ "#txt_city") (note: the parameter is a string, not a keyword).

Also, look to the reagent tests themselves for inspiration: https://github.com/reagent-project/reagent/blob/master/test/reagenttest/testreagent.cljs



回答2:

The answer is cljs-react-test:

(deftest choose-city-component-test-out
  (let [comp (r/render-component [w/choose-city-component]
                             (. js/document (getElementById "test")))
    expected-invocations (atom [])]
    (with-redefs [weather-app.core/fetch-weather #(swap! expected-invocations conj %)]
      ;;GIVEN render component in test
      ;;WHEN changing the city and submitting  
      (sim/change (sel1 :#txt_city) {:target {:value "london"}})
      (sim/click  (sel1 :#btn_go) nil)
      ;;ASSERT london should be sent to fetch-weather
      (is (=["london"] @expected-invocations))
      )))

where we use:

   [cljs-react-test.simulate :as sim]
   [dommy.core :as dommy :refer-macros [sel1 sel]]

and in project.clj

 :dependencies [[org.clojure/clojure "1.7.0"]
             [org.clojure/clojurescript "1.7.170"]
             [org.clojure/core.async "0.2.374"]
             [reagent "0.5.1" :exclusions [cljsjs/react]]
             [cljs-react-test "0.1.3-SNAPSHOT"]
             [cljsjs/react-with-addons "0.13.3-0"]
             [cljs-ajax "0.5.2"]
             [jayq "2.5.4"]]