How to use uTest-wrapping with scalajs sbt test to test async events?

77 Views Asked by At

I tried the uTest test wrapping in GitHub with the following code:

object AjaxExp01SOTest extends TestSuite {

  val log = JSLog.getLogger(getClass().getSimpleName)
  JSLog.setGlobalLevel(Level.DEBUG)

  def tests = TestSuite {

    "OK: GET slP" - {

      val promise = Promise[XMLHttpRequest]

      val callback: (dom.Event, XMLHttpRequest ) => Unit = { (e,x) =>
            log.debug("callback running...")
            log.debug("res.status = " + x.status + "   res.responseText = " + x.responseText )
            promise.success(x)
      }

      def send( method: String, url: String, isAsync: Boolean, timeout: Long, 
      requestHeader: String, requestHeaderValue: String, 
      data: String, callback: (dom.Event, XMLHttpRequest ) => Unit ): XMLHttpRequest = {
            val xhr = new dom.XMLHttpRequest()
            xhr.open(method, url, isAsync )
            xhr.timeout = timeout
            if ( requestHeader != null) {
              xhr.setRequestHeader(requestHeader, requestHeaderValue)
            }
            def cb(e: dom.Event): Unit = { callback(e,xhr) }
            xhr.onload = cb _
            if ( data != null) {
              xhr.send(data)
            } else {
              xhr.send()
            }
            xhr
      }

      log.debug("send begin")
      val url = "http://localhost:9000/slG/124"
      val res = send("GET", url, true, 0, null, null, null, callback)
      log.debug("send end")

      promise.future
    }

  }

  override def utestWrap(runBody: => concurrent.Future[Any])
           (implicit ec: ExecutionContext): concurrent.Future[Any] = {
    val f = runBody
    f.onComplete {
      case Success(a) if ( a != null )=> { log.debug("SUCCESS " + a.getClass.getSimpleName) } // BoxedUnit,
      case Success(a) => { log.debug("SUCCESS a == null") }
      case Failure(a) => log.debug("FAILURE")
    }
    log.debug("utestWrap begin")
    f
  }
}

It has this results:

21:03:23.164 DEBUG AjaxExp01SOTest - SUCCESS BoxedUnit
21:03:23.168 DEBUG AjaxExp01SOTest - utestWrap begin
21:03:23.172 DEBUG AjaxExp01SOTest - OK: GET slP   *****
21:03:23.174 DEBUG AjaxExp01SOTest - send begin
21:03:23.177 DEBUG AjaxExp01SOTest - send end
21:03:23.180 DEBUG AjaxExp01SOTest - utestWrap begin

Client sent the GET request to server which replied after a delay but client's callback was never called. Test was stuck on waiting callback to be called.

What's wrong in this code? Most likely the utestWrap has an error or other misunderstanding.

Another (minor) question is that what is the "SUCCESS BoxedUnit"? There is only one test case "GET slP" in the TestSuite which starts after "SUCCESS BoxedUnit" and never reaches "SUCCESS XMLHttpRequest".

0

There are 0 best solutions below