Unit testing in Kotlin/JS

It seems the compiler has special support for @Test and @Ignore, and generates top level calls for these inside the generated javascript.


  package$js.main = main;
  package$js.FibTestsKotlinTest = FibTestsKotlinTest;
  package$js.FibTestsSdk = FibTestsSdk;
  package$js.FunSpec = FunSpec;
  suite('io.kotlintest.example.mpp.js', false, function () {
    suite('FibTestsSdk', false, function () {
      test('fibTests', false, function () {
        return (new FibTestsSdk()).fibTests();
  Kotlin.defineModule('kotlintest-example-multiplatform_test', _);
  return _;

If I could find out a way to also generate code at the top level like this, then I think I would have enough to implement KotlinTest for JS.

@sksamuel The important bit is suite(...) The suite and test invocations don’t have to be top-level. They just need to be invoked at some point after module initialization.

I don’t think there is a sane way to achieve that though. The following text describes an approach which might work, but requires quite some effort to implement.

One possibility is to abuse test inheritance. Basically it is possible to inherit tests from a base class or interface (see this test)

So I think you could try doing the following:

  • Add a @Test dummyTest() { <launch your custom tests here> } to StringSpec
  • The compiler will generate a test("dummyTest", false, ...) for each successor
  • When dummyTest is invoked launch your custom tests

There are at least two problems with this scheme

  • You get some garbage in the test hierarchy (“dummyTest”)
  • I suspect that test frameworks might not like suites within tests

In order to solve those issues you might want to replace the test adapter with some custom implementation, which would filter out the dummyTest tests and delegate to the original test adapter when needed. (example of complex test adapter)

Your suggestion is exactly what I did last night. Custom framework adapter that looks for the dummy name and instead calls other tests.

Good job )

Do you know if there’s a way to add the adapter.js file from a dependency, so it doesn’t have to be added manually to every proejct ?

Why not just set up the adapter during KotlinTest initialization? Am I missing something?

I mean, whoever is going to use KotlinTest will require it. Thus changing the test adapter during KotlinTest module initialization seems like a perfectly good solution to me.

Also the test adapter doesn’t have to a separate .js file. It can be done in Kotlin, albeit you’ll have to jump through some hoops.

If you do have it in a separate .js file, why not make the KotlinTest module depend on in? I.e. you require the adapter.js, it configures kotlin-test.