Rahel Lüthy
Rahel Lüthy

Reputation: 7007

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?

Upvotes: 14

Views: 958

Answers (1)

Suma
Suma

Reputation: 34423

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.

Upvotes: 5

Related Questions