How can I test scala.js programs for side effects that happen asynchronously using μtest?

I have a μtest package that is supposed to check that some asynchronous operation eventually has a side effect. Since javascript (and thus scala.js) is single threaded, it is not possible to block and wait for a side effect. Also, the μtest method does eventually

not work in the javascript runtime. How do you perform such a test?

+3


source to share


1 answer


If you return Future

from μtest, then the test will pass if the future succeeds and fail if the future fails. This way, you can schedule a conditional check at some point in the future without blocking.

I wrote a simple method eventually

that accomplishes this:

package utest

import rx.ops.DomScheduler

import scala.concurrent.{Promise, Future}
import scala.concurrent.duration.FiniteDuration
import scala.util.{Failure, Success, Try}

object JsOps {
  import scala.concurrent.ExecutionContext.Implicits.global
  val scheduler = new DomScheduler

  def eventually(eval: => Try[Boolean])(implicit timeout: FiniteDuration): Future[Boolean] = {
    val p = Promise[Boolean]()
    scheduler.scheduleOnce(timeout) {
      eval match {
        case Success(b) => p.success(b)
        case Failure(t) => p.failure(t)
      }
    }
    p.future
  }
}

      



Here's a usage example:

  import scala.concurrent.duration._
  implicit val timeout = 30.milliseconds

  eventually {
    if (/*condition holds true*/) {
      Success(true)
    } else Failure(new RuntimeException(/*error message*/))
  }

      

+3


source







All Articles