Skip to content

Instantly share code, notes, and snippets.

@geraldodev
Last active June 29, 2023 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geraldodev/001b3dc5f8888cd9e8847d45d185c1fd to your computer and use it in GitHub Desktop.
Save geraldodev/001b3dc5f8888cd9e8847d45d185c1fd to your computer and use it in GitHub Desktop.
(ns js-cljs.astutils-test
(:require
["./../../src/js_cljs/astutils" :refer [tagFunctionNodesAsReactComponent]]
["@babel/traverse$default" :as traverse]
[clojure.test :refer [deftest is testing]]
[js-cljs.core :refer [babel-parse]]
[applied-science.js-interop :as j]
))
(deftest react-function-tagging
(let [flags (atom {})
ast (babel-parse
"
function MyComponent() {
return <div>Hello, World!</div>;
}
const MyArrowComponent = () => {
return <div>Hello, World!</div>;
};
const MyArrowComponentJustJsx = () => <div>Hello, World!</div>;
const CamelCaseNotReact = () => {
return 1;
};
function FunctionNotReact() {
return 1;
}
")
]
(tagFunctionNodesAsReactComponent ast)
((.-default traverse)
ast #js {:FunctionDeclaration
(fn [path]
(let [name (j/get-in path [:node :id :name])
is-react-component (j/get-in path [:node :isReactComponent] false)]
(swap! flags assoc (keyword name) is-react-component))
;; babel, complains if return the result is result of swap! expression
nil)
;; since we are using name of variable to flag ArrowFunctionExpression
;; to sinalize that the VariableDeclarator has a isReactComponent flag
;; we are using `NameOfVariableVariableDeclarator`
:VariableDeclarator
(fn [path]
(let [name (j/get-in path [:node :id :name])
test-name (keyword (str name "VariableDeclarator"))
is-react-component (j/get-in path [:node :isReactComponent] false)]
(swap! flags assoc test-name is-react-component))
;; babel, complains if return the result is result of swap! expression
nil)
:ArrowFunctionExpression
(fn [path]
;; ArrowFunction does not have a name so we lookup
;; it's variable if any, and flag it's name
(when-let [variableDeclarator (.findParent path #(.isVariableDeclarator %))]
(let [name (j/get-in variableDeclarator [:node :id :name])
is-react-component (j/get-in path [:node :isReactComponent] false)]
(swap! flags assoc (keyword name) is-react-component)) )
;; babel, complains if return the result is result of swap! expression
nil) })
(testing "tagging ast nodes"
(is (= (:MyComponent @flags) true))
(is (= (:FunctionNotReact @flags) false))
(is (= (:MyArrowComponent @flags) true))
(is (= (:MyArrowComponentVariableDeclarator @flags) true))
(is (= (:MyArrowComponentJustJsx @flags) true))
(is (= (:MyArrowComponentJustJsxVariableDeclarator @flags) true))
(is (= (:CamelCaseNotReact @flags) false))
(is (= (:CamelCaseNotReactVariableDeclarator @flags) false))
)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment