It isn’t easy to find how-to run tests written with cljs.test, and one of desired
ways to run tests — run them from a terminal (or on a ci server). And it’s
simple with phantomjs, first of all you need to configure cljsbuild
. It config
in project.clj
should be like:
:cljsbuild {:builds {:test {:source-paths ["src" "test"]
:compiler {:output-to "resources/test/compiled.js"
:optimizations :whitespace
:pretty-print true}}}
:test-commands {"test" ["phantomjs"
; Files will be crated later:
"resources/test/test.js"
"resources/test/test.html"]}}
And fill resources/test/test.js
with something like:
var page = require('webpage').create();
var url = phantom.args[0];
page.onConsoleMessage = function (message) {
console.log(message);
};
page.open(url, function (status) {
page.evaluate(function(){
// Use your namespace instead of `cljs-test-example`:
cljs_test_example.test.run();
});
phantom.exit(0);
});
Then fill resources/test/test.html
with:
<!DOCTYPE html>
<html>
<head>
<script src="compiled.js"></script>
</head>
</html>
And create test.cljs
in your tests root with your app namespace instead of
cljs-test-example
and with run
function for running all tests:
(ns cljs-test-example.test
(:require [cljs.test :refer-macros [run-all-tests]]))
(enable-console-print!)
(defn ^:export run
[]
(run-all-tests #"cljs-test-example.*-test"))
And now you can run your tests:
➜ lein cljsbuild test
Compiling ClojureScript.
Running ClojureScript test: test
Testing cljs-test-example.core-test
Ran 1 tests containing 1 assertions.
0 failures, 0 errors.
Another popular approach is to run tests when source code changed, it can be easily done with figwheel. You just need to configure figwheel to run tests when js loaded:
:cljsbuild {:builds {:main {:source-paths ["src" "test"]
; Runs tests on every change:
:figwheel {:on-jsload "cljs-test-example.test/run"}
:compiler {:output-to "resources/public/compiled/main.js"
:output-dir "resources/public/compiled"
:asset-path "/compiled"
:main "cljs-test-example.core"
:source-map true
:optimizations :none
:pretty-print false}}}}
Add ^:figwheel-always
metadata to the namespace with function for running tests, like:
(ns ^:figwheel-always cljs-test-example.test
(:require [cljs.test :refer-macros [run-all-tests]]))
And add ^:figwheel-load
to all namespaces with tests, like:
(ns ^:figwheel-load cljs-test-example.core-test
(:require [cljs.test :refer-macros [deftest is]]
[cljs-test-example.core :refer [do-something-x-y]]))
Then you can see tests results in your browser console, like: