Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing Scala.js: Read test data from file residing in `test/resources`

In a Scala.js unit test, what is the easiest solution to load test data from a file residing in test/resources?

like image 226
Rahel Lüthy Avatar asked Nov 29 '16 13:11

Rahel Lüthy


1 Answers

It turns out at least with recent Scala.js (0.6.14 and 0.6.15 tested) and Node.js (7.8.0 tested) the situation is simple. As tests are ran using Node runner by default, one can use Node.js sync file operations and read the file using fs readFileSync. A function handling this can look like:

  def rscPath(path: String): String = "src/test/resources/" + path

  def rsc(path: String): String = {
    import scalajs.js.Dynamic.{global => g}
    val fs = g.require("fs")

    def readFile(name: String): String = {
      fs.readFileSync(name).toString
    }

    readFile(rscPath(path))
  }

  val testInput = rsc("package/test-input.txt")

Instead of loading them directly from src/test/resources, one could also load them from target/scala-2.12/test-classes as the files are copied there by the SBT build. I think I would prefer this if I could find some simple API how to obtain this path, so that it does not have to be hardcoded in the rscPath function.

like image 109
Suma Avatar answered Oct 05 '22 23:10

Suma