unit-testing - 如何正确(单元)测试 On/React 组件?

标签 unit-testing reactjs clojurescript om

我开发了 Om/React 组件,但无法通过单元测试来驱动我的开发,我感到非常不舒服。我尝试设置我的 clojurescript 项目来对这些组件运行单元测试,到目前为止我已经能够编写单元测试并实例化我的组件了。我缺少的是确保我的组件对某些事件做出正确 react 的能力,例如onChange 以便我可以模拟用户输入。

这是我的测试代码:

(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))
      )))

此测试运行但失败,因为 change-field! 函数实际上并未更改组件的状态。这是组件的(部分)代码(请原谅重复......):

(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")))))

通过在测试中添加跟踪,我可以看到,当我触发 change 事件时,组件的状态并未更新,尽管它已正确触发。我怀疑这与 Om/React 的工作方式有关,包装 DOM 组件,但不知道如何处理这个问题。

最佳答案

您可以使用 React 库中的 ReactTestUtils 来模拟组件中的事件。 我正在使用 mocha 并执行类似的操作来测试更改事件:

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); 
}

关于unit-testing - 如何正确(单元)测试 On/React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210474/

相关文章:

c++ - C++ 的 CATCH 单元测试比较 std::array

unit-testing - 如何在Grails测试中填充有效参数

reactjs - 如何在父组件中更新正确的状态值,该父组件使用 react 中的钩子(Hook)从子组件获取其值?

css - 滚动时在 React Sticky 中制作一个 Material UI 组件(不是 AppBar)

clojurescript - 如何为 clojurescript 创建宏

javascript - 错误: Expected spy create to have been called

javascript - AngularJS单元测试: using async/await with Jasmine

reactjs - 尝试根据当前 session 加载部分主应用程序布局时出现 SSR 警告

clojure - core.async channel 上的传感器

clojure - 如何使用 Figwheel 设置 Atom 编辑器以进行 clojurescript 开发?