如何使用scalajs sbt test进行uTest-wrapping来测试异步事件?

时间:2016-03-29 06:58:58

标签: scala sbt scala.js utest

我使用以下代码尝试了GitHub 中的uTest测试包装:

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
  }
}

结果如下:

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

客户端将GET请求发送到服务器,该服务器在延迟后回复,但从未调用过客户端的回调。测试停留在等待回调被调用。

此代码有什么问题?很可能utestWrap有错误或其他误解。

另一个(次要)问题是什么是" SUCCESS BoxedUnit"?只有一个测试案例" GET slP"在" SUCCESS BoxedUnit"之后开始的TestSuite中永远不会达到"成功XMLHttpRequest"。

0 个答案:

没有答案