Search code examples
javascriptclojurescript

How to declare javascript object with constructor in clojurescript


My code works with realm library and at some point it calls realm constructor:

(dependencies/realm. (clj->js options))

Realm was declared like this:

(def realm (js/require "realm"))

Right now I want to temporarily mock realm object to not make calls to library. I tried this approach:

(def realm  #js {:schemaVersion (fn [])
                 :close         (fn [])})

It worked well for mocking close() and schemaVersion() functions but I'm getting error dependencies.realm is not a constructor.

How can I add constructor declaration to realm object placeholder?

Thanks.


Solution

  • In javascript a constructor is a function. Instead, you should have a function that returns an object:

    (def realm (fn [] #js {}))
    

    I assume schemaVersion and close are static methods. You can add them later with:

    (goog.object/extend realm #js {:schemaVersion (fn [])
                                   :close         (fn [])})