LoginSignup
7
5

More than 5 years have passed since last update.

ClojureScriptでテストを書く

Last updated at Posted at 2017-08-15

ClojureScriptでテストを書く必要があったので最低限必要な物をまとめてみた。

ミニマルなテストコード

  • Clojureに同梱されているclojure.testは、ClojureScriptにポートされていてcljs.testとして同梱されている。
  • ClojureScriptのOSSでも幅広く使用されており、これを使用するのが間違いないので使用する。
(ns myapp.test
  (:require  [cljs.test :as t]))

(enable-console-print!)

(t/deftest test-foo
  (t/is (= 1 1)))

;; Runs tests in current ns
(t/run-tests)

ビルドする

ClojureScriptがクラスパスにある前提で、以下をREPLで実行する。
(ここではjvmのClojureScriptを使うが、lumoビルドapiも同様に使用できるはず)

(require '[cljs.build.api :as b])
(b/build "test" ;; Directory containing the test code
         {:main 'myapp.test ;;The ns that includes the tests
          :output-to "out/test.js" ;;Output file name
          :optimizations :simple ;; Convenient to have a single file output
          })

ブラウザで実行

  • 以下のようなhtmlファイルを作成し、スクリプトタグをビルドしたjsファイルを指すようにし、そのhtmlファイルをブラウザで開くと実行できる。
  • 実行結果はコンソールに出力される
<!DOCTYPE html>
<html>
  <head>
    <title>fiddles</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
  <body>
    <script src="out/test.js" type="text/javascript"></script>
  </body>
</html>

nodejsで実行

  • 起動が早いメリットがある
  • node out/test.jsのように実行する
  • ビルドの設定に:target :nodejsを含める(今回の例は単純なので無くても動く)
(require '[cljs.build.api :as b])
(b/build "test" ;; Directory containing the test code
         {:main 'myapp.test ;;The ns that includes the tests
          :output-to "out/test.js" ;;Output file name
          :target :nodejs ;;when targeting node
          :optimizations :simple ;; Convenient to have a single file output
          })

nashornで実行

  • jdk8を使用していればjjs path/to/file/test.jsのようにして実行することができる。
  • メリットは、jdkに同梱されているので外部の何かをインストールする必要が無いこと
  • デメリットは起動がもっさりしていること
  • jjs out/test.jsのように実行する
  • プリントに使用されるデフォルトのconsoleオブジェクトが存在しないため、(set! *print-fn* js/print) を含める必要がある。
    • 含めていない場合、ReferenceError: "console" is not definedというエラーが表示される
(ns myapp.test
  (:require  [cljs.test :as t]))

(set! *print-fn* js/print)

(t/deftest test-foo
  (t/is (= 1 1)))

;; Runs tests in current ns
(t/run-tests)

複数のテストnsをまとめて実行する

こういう風に書ける。

(ns myapp.test-runner
  (:require [cljs.test :as t]
            [bar.test]
            [foo.test]))

(enable-console-print!)

(t/run-tests 'bar.test
             'foo.test)

ossでの例

TODO

他にもlein-cljsbuildtとかlein-dooとdevcardsが便利っぽいのでそのうち調べたい

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5