Fork me on GitHub
#re-frame
<
2022-01-14
>
rgm01:01:43

hi all ... is there a straightforward way to mock out re-frame's globals so that I can use kaocha and node to test some non-DOM-related code in a namespace that requires re-frame? My kaocha-cljs suite breaks the instant I add a test that requires a re-frame containing namespace, based on not being able to find `xmlhttprequest` and `window`. Looks like just adding the xmlhttprequest and window npms isn't helping. I'm thinking including a simple JS file that has `window = {}` (no `var` or `let` thus global) would do it here. I'm going with node because mostly we're testing non-DOM-related logic and I find it hard to justify adding browser flakiness to the units when we have a separate browser-based suite that does hit real re-frame.

lispers-anonymous04:01:52

Depends on your build tooling. I use shadow-cljs and have this line in my :test build (which is a :node-test target)

:devtools   {:preloads [my.test-preloads]}

lispers-anonymous04:01:01

Inside the my.test-preloads namespace is this code

(defn global-stubs!
  []
  (let [make-element (fn [_]
                       (clj->js
                         {:setAttribute (fn [_] [])
                          :insertBefore (fn [_] [])}))]
    (set! (.-document js/global)
          (clj->js {:getElementById make-element
                    :getElementsByClassName make-element
                    :createStyle make-element
                    :createElement make-element
                    :querySelector make-element
                    :head (make-element nil)})))
  (set! (.-window js/global)
        (clj->js {:location {:href ""}}))
  (set! (.-navigator js/global) (clj->js {:userAgent ""}))
  (set! (.-crypto js/global) (clj->js {}))
  (set! (.-history js/global)
        (clj->js {:back (fn [])
                  :forward (fn [])
                  :go (fn [])})))

(global-stubs!)
This mocks out all the browser functionality that are tests can encounter.

rgm04:01:40

oh thanks ... didn't even consider a preload. Kaocha-cljs lets me set up compiler options so I think I can wedge the setting in there https://clojurescript.org/reference/compiler-options#preloads