Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly (unit) test Om/React components?

I have developed Om/React components, but I feel really uncomfortable not being able to drive my development with unit tests. I have tried to setup my clojurescript project to run unit tests on those components, and so far reached the point where I am able to write unit tests and instantiate my components. What I am missing is the ability to ensure my components properly react to some events, e.g. onChange so that I can simulate user inputs.

Here is my test code:

(defn simulate-click-event
  "From https://github.com/levand/domina/blob/master/test/cljs/domina/test.cljs"
  [el]
  (let [document (.-document js/window)]
    (cond
     (.-click el) (.click el)
     (.-createEvent document) (let [e (.createEvent document "MouseEvents")]
                                (.initMouseEvent e "click" true true
                                                 js/window 0 0 0 0 0
                                                 false false false false 0 nil)
                                (.dispatchEvent el e))
     :default (throw "Unable to simulate click event"))))

(defn simulate-change-event
  "From https://github.com/levand/domina/blob/master/test/cljs/domina/test.cljs"
  [el]
  (let [document (.-document js/window)]
    (cond
     (.-onChange el) (do (print "firing on change on "  el) (.onChange el))
     (.-createEvent document) (let [e (.createEvent document "HTMLEvents")]
                                (print "firing  " e " on change on "  (.-id el))
                                (.initEvent e "change" true true)
                                (.dispatchEvent el e))
     :default (throw "Unable to simulate change event"))))

(def sink
  "contains a channel that receives messages along with notification type"
  (chan))

;; see http://yobriefca.se/blog/2014/06/04/publish-and-subscribe-with-core-dot-asyncs-pub-and-sub/
(def source
  (pub sink #(:topic %)))

(defn change-field!
  [id value]
  (let [el (sel1 (keyword (str "#" id)))]
     (dommy/set-value! el  value)
     (simulate-change-event el)
     ))

(deftest ^:async password-confirmation
  (testing "do not submit if passwords are not equal"
    (let [subscription (chan)]
      (sub source :user-registration subscription)
      (om/root
       (partial u/registration-view source sink)
       nil
       {:target (sel1 :#view)})

      (go
       (let [m (<! subscription)]
         (is (= :error (:state m)))
         (done)
         ))

      (change-field! "userRequestedEmail"    "[email protected]")
      (change-field! "userRequestedPassword" "secret")
      (change-field! "confirmPassword"       "nosecret")

      (simulate-click-event (sel1 :#submitRegistration))
      )))

This test runs but fails because the change-field! function does not actually change the state of the component. Here is (part of) the code of the component (forgive duplication...):

(defn registration-view
  "Registration form for users.

  Submitting form triggers a request to server"
  [source sink _ owner]
  (reify

    om/IInitState
    (init-state [_]
                {:userRequestedEmail ""
                 :userRequestedPassword ""
                 :confirmPassword ""}
                )

    om/IRenderState
    (render-state
     [this state]
     (dom/fieldset
      nil
      (dom/legend nil "User Registration")
      (dom/div #js { :className "pure-control-group" }

               (dom/label #js { :for "userRequestedEmail" } "EMail")
               (dom/input #js { :id "userRequestedEmail" :type "text" :placeholder "Enter an e-mail"
                                :value (:userRequestedEmail state)
                                :onChange #(om/set-state! owner :userRequestedEmail (.. % -target -value))}))

      (dom/div #js { :className "pure-control-group" }
               (dom/label #js { :for "userRequestedPassword" } "Password")
               (dom/input #js { :id "userRequestedPassword" :type "password" :placeholder "Enter password"
                                :value (:userRequestedPassword state)
                                :onChange #(om/set-state! owner :userRequestedPassword (.. % -target -value))}))

      (dom/div #js { :className "pure-control-group" }
               (dom/label #js { :for "confirmPassword" } "")
               (dom/input #js { :id "confirmPassword" :type "password" :placeholder "Confirm password"
                                :value (:confirmPassword state)
                                :onChange #(om/set-state! owner :confirmPassword (.. % -target -value))}))


      (dom/button #js {:type "submit"
                       :id "submitRegistration"
                       :className "pure-button pure-button-primary"
                       :onClick #(submit-registration state sink)}
                  "Register")))))

What I can see by putting traces in the tests is that the state of the component is not updated when I trigger the change event, although it is correctly triggered. I suspect this has to do with the way Om/React works, wrapping DOM components, but not sure how to deal with this.

like image 982
insitu Avatar asked Oct 06 '14 05:10

insitu


People also ask

How do you unit test React Redux components?

Ultimately, that's already it for testing the second part of the connected react-redux component: 1) Provide State -> React Component (Unit Test) => Component Renders. 2) React Component (Unit Test) -> Simulate Event => Dispatch Action Triggers.

How do you structure a unit test?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.

How would you test the React components using jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

What should be tested in a React app?

The entire testing process for a react app involves unit testing, component testing, end-to-end testing, and cross browser compatibility testing. Some of the methods to test React Apps are mentioned below using examples.


1 Answers

You can mock events in your components using ReactTestUtils from the react libraries. I'm using mocha and doing something like this to test change events:

var comp = ReactTestUtils.renderIntoDocument(<Component />);
var changingElement = ReactTestUtils.findRenderedDOMComponentWithClass(comp, 'el-class'); 
it ('calls myChangeMethod on change', function() {
  ReactTestUtils.Simulate.change(changingElement);
  assert(comp.myChangeEventMethod.called, true); 
}
like image 119
user874639 Avatar answered Oct 12 '22 22:10

user874639