Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test Kotlin code when compiling to JavaScript?

Tags:

kotlin

I have a Kotlin JavaScript project in IntelliJ (Ultimate). I want to be able to write tests for this project.

I have tried a number of different things ranging from writing tests with Spek (this would be ideal) to writing them in Karma/Jasmine. The problem with Spek is that I could not get it to work with a JavaScript project. It complains about some jars not being a JavaScript library.

The problem with Karma/Jasmine is that I couldn't figure out how to get the test runner to pick up the tests from my Kotlin test output. When the tests are written in plain JavaScript, they can't access my Kotlin objects because I don't know how to reference them correctly with all of the name mangling that occurs when you do Kotlin to JavaScript compilation.

I'm open to anything at the moment, since this is an Angular project, I can probably figure out how to do end-to-end testing with Protractor, though I would really prefer some unit test coverage.

like image 271
Micah Zoltu Avatar asked Feb 17 '15 05:02

Micah Zoltu


1 Answers

Below You can find simple test which I write using QUnit. I believe that You can do the same for other libraries. Moreover it can be improved by making it more type safe.

main.kt:

native("QUnit") val qunit: dynamic
val assert = qunit.assert

fun main(args: Array<String>) {

    qunit.test( "hello test")  { assert ->
        val t: Any = "1"
        assert.ok(1 == t, "Passed!")
    }

    qunit.test( "hello test")  {
        assert.ok(1 == 1, "Passed!")
    }
}

runner.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>QUnit Example</title>
    <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-1.17.1.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-1.17.1.js"></script>
<script src="lib/kotlin.js"></script>
<script src="js_test.js"></script>
</body>
</html>
like image 187
bashor Avatar answered Oct 20 '22 04:10

bashor