Add componentDidCatch support and test (error boundary)

This commit is contained in:
Juho Teperi 2017-10-13 19:20:36 +03:00
parent c68f5a88f4
commit 39b0326d22
2 changed files with 30 additions and 3 deletions

View File

@ -199,6 +199,10 @@
(when-not (nil? f)
(.call f c c))))
:componentDidCatch
(fn componentDidCatch [error info]
(this-as c (.call f c c error info)))
nil))
(defn get-wrapper [key f name]
@ -268,9 +272,11 @@
create-react-class))
(defn component-path [c]
(let [elem (some-> (or (some-> c ($ :_reactInternalInstance))
c)
($ :_currentElement))
;; Looks like in React 16, reactInternalFiber is the elem
(let [elem (or (some-> c ($ :_reactInternalFiber))
(some-> (or (some-> c ($ :_reactInternalInstance))
c)
($ :_currentElement)))
name (some-> elem
($ :type)
($ :displayName))

View File

@ -1,5 +1,6 @@
(ns reagenttest.testreagent
(:require [cljs.test :as t :refer-macros [is deftest testing]]
[react :as react]
[create-react-class :as create-react-class]
[reagent.ratom :as rv :refer-macros [reaction]]
[reagent.debug :as debug :refer-macros [dbg println log dev?]]
@ -964,6 +965,26 @@
(is (re-find #"Every element in a seq should have a unique :key"
(-> e :warn first))))))))
(deftest test-error-boundary
(when (>= (js/parseInt react/version) 16)
(let [error (r/atom nil)
error-boundary (fn error-boundary [comp]
(r/create-class
{:component-did-catch (fn [this e info]
(reset! error e))
:reagent-render (fn [comp]
(if @error
[:div "Something went wrong."]
comp))}))
comp1 (fn comp1 []
($ nil :foo)
[:div "foo"])]
(with-mounted-component [error-boundary [comp1]]
(fn [c div]
(r/flush)
(is (= "Cannot read property 'foo' of null" (.-message @error)))
(is (found-in #"Something went wrong\." div)))))))
(deftest test-dom-node
(let [node (atom nil)
ref (atom nil)