14

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

Suma
  • 33,181
  • 16
  • 123
  • 191
Rahel Lüthy
  • 6,837
  • 3
  • 36
  • 51
  • A bit of trouble here is `fs` operations are asynchronous, but they are not executed on an `ExecutionContext` known to the testing framework. Simply building a Future from a Promise does not work - see [ScalaTest issue #1039](https://github.com/scalatest/scalatest/issues/1039) – Suma Feb 09 '17 at 13:12
  • Duplicate of http://stackoverflow.com/questions/40291805/how-do-a-read-a-resource-file-in-scala-js ? – Rich Feb 12 '17 at 16:10
  • 1
    @Rich It is similar, but tests brings specific issues regarding handling async operations. – Suma Feb 12 '17 at 19:35

1 Answers1

5

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.

Suma
  • 33,181
  • 16
  • 123
  • 191