我采用的方法一方面可以很容易地在测试中禁用动画,另一方面 - 不需要每个动画组件支持任何特定于测试的参数。
由于我使用 ClojureScript,因此某些人可能不熟悉语法,但我将对其进行注释以使其更清晰:
;; By default, in non-unit-test code, animations are enabled.
(def ^:dynamic animations-enabled true)
;; Custom component that essentially wraps React.addons.CSSTransitionGroup,
;; but modifies props passed to it whenever animations-enabled
;; is set to false.
(def css-transition-group
(let [rc-anim-cls (rc/adapt-react-class js/React.addons.CSSTransitionGroup)]
(rc/create-class
{:reagent-render
(fn [anim-spec & children]
(let [anim-spec-2 (if animations-enabled
;; If animations are enabled,
;; pass props through with no change.
anim-spec
;; If animations are disabled,
;; override that in props before passing
;; them to CSSTransitionGroup.
(assoc anim-spec
:transition-enter false
:transition-leave false))]
(into [rc-anim-cls anim-spec-2] children)))})))
在常规代码中,此类的使用方式与使用标准的方式完全相同CSSTransitionGroup
。
然而,在单元测试中,我可以绑定animations-enabled
为false
并安全地断言正在添加/删除的 DOM 元素:
(binding [anim/animations-enabled false]
;; Create component that uses animations. It will not be
;; animated though.
)