SBT退出失败的业力测试

时间:2016-06-02 11:20:48

标签: unit-testing sbt karma-jasmine

我在Play框架上运行了一个角度应用程序。 我在我的Karma / Jasmine测试套件中添加并使用以下build.sbt配置将其作为“sbt test”的一部分运行...

// run the angular JS unit tests (karma & jasmine)
lazy val jsTest = taskKey[Int]("jsTest")
jsTest in Test := {
    "test/js/node_modules/karma/bin/karma start karma.conf.js" !
}
test := Def.taskDyn {
    val exitCode = (jsTest in Test).value
    if (exitCode == 0)
    Def.task {
        (test in Test).value
    }
    else Def.task()
}.value

但是,如果其中一个测试失败,则sbt似乎不会退出...

Chrome 50.0.2661 (Mac OS X 10.10.5): Executed 90 of 90 (1 FAILED) (0.512 secs / 0.453 secs)
[success] Total time: 3 s, completed 02-Jun-2016 12:11:13

运行sbt测试后,我也运行sbt dist,如果任何测试失败,我不希望发生这种情况。如果JS或scala测试失败,我希望sbt退出。

谢谢!

1 个答案:

答案 0 :(得分:2)

即使来自Karma的退出代码不是test,您似乎也让SBT 0任务成功。最简单的解决方法是在这种情况下抛出异常,SBT会在任务失败时检测到它:

  lazy val jsTest = taskKey[Int]("jsTest")
  jsTest in Test := {
    "test/js/node_modules/karma/bin/karma start karma.conf.js" !
  }
  test := Def.taskDyn {
    val exitCode = (jsTest in Test).value
    if (exitCode == 0)
      Def.task {
        (test in Test).value
      }
    else sys.error("Karma tests failed with exit code " + exitCode)
  }.value

但现在你处于一种奇怪的情况,即使测试失败,jsTest任务在技术上仍然成功。让jsTest任务检查错误代码更合适,而test任务依赖于它:

  lazy val jsTest = taskKey[Unit]("jsTest")
  jsTest in Test := {
    val exitCode = "test/js/node_modules/karma/bin/karma start karma.conf.js" !
    if (exitCode != 0) {
      sys.error("Karma tests failed with exit code " + exitCode)
    }
  }
  test := Def.taskDyn {
    (jsTest in Test).value
    Def.task((test in Test).value)
  }.value

如果您确保JS测试和Scala测试并行运行,那么您可以进一步简化它:

  lazy val jsTest = taskKey[Unit]("jsTest")
  jsTest in Test := {
    val exitCode = "test/js/node_modules/karma/bin/karma start karma.conf.js" !
    if (exitCode != 0) {
      sys.error("Karma tests failed with exit code " + exitCode)
    }
  }
  test := {
    (jsTest in Test).value
    (test in Test).value
  }