简体   繁体   English

如何正确(单位)测试Om / React组件?

[英]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. 我已经开发了Om / React组件,但是无法通过单元测试来驱动我的开发我感到非常不舒服。 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. 我尝试设置clojurescript项目以在那些组件上运行单元测试,到目前为止,我已经能够编写单元测试和实例化组件。 What I am missing is the ability to ensure my components properly react to some events, eg onChange so that I can simulate user inputs. 我缺少的是确保我的组件对某些事件(例如onChange正确反应的能力,以便我可以模拟用户输入。

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"    "foo@bar.com")
      (change-field! "userRequestedPassword" "secret")
      (change-field! "confirmPassword"       "nosecret")

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

This test runs but fails because the change-field! 该测试运行,但由于change-field!而失败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. 通过在测试中放置跟踪信息,我可以看到的是,尽管我正确地触发了change事件,但组件的状态并未更新。 I suspect this has to do with the way Om/React works, wrapping DOM components, but not sure how to deal with this. 我怀疑这与Om / React的工作方式有关,包装了DOM组件,但不确定如何处理。

You can mock events in your components using ReactTestUtils from the react libraries. 您可以使用react库中的ReactTestUtils在组件中模拟事件。 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); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM