简体   繁体   English

带有 Play 框架的 ScalaJs(测试错误)

[英]ScalaJs With Play Framework (Error in Tests)

I am trying to use ScalaJs cross build project with Play Framework 2.5.我正在尝试在 Play Framework 2.5 中使用 ScalaJs 交叉构建项目。 I am facing a problem when I am trying to run the tests for Client.scala .当我尝试运行 Client.scala 的测试时,我遇到了一个问题。 The error I am getting is -我得到的错误是 -

caused by: TypeError: Cannot call method "appendChild" of null .引起:类型错误:无法调用 null 的方法“appendChild”。

Client snippet客户端片段

@JSExport
object DashboardClient extends js.JSApp {
@JSExport
def main(): Unit = {
val dashboard = new Dashboard
dom.document.getElementById("bodyContent").appendChild(dashboard.bodyFrag.render)
}

This bodyFrag is inside a different class这个 bodyFrag 在一个不同的类中

 def bodyFrag =
div(
  div(
    `class` := "row border-bottom",
    div(
      `class` := "col-md-12",
      div(
        `class` := "col-md-2 image-alignment",
        img(width := "161", src := "/assets/images/mountain.jpg")
      ),
      div(`class` := "col-md-10")
    )
  ),
  div(
    `class` := "row border-bottom",
    div(
      `class` := "col-md-12",
      div(
        `class` := "col-md-12",
        h1(`class` := "text-center", "Dashboard")
      )
    )
  )
)

So when I am trying to test is using utest I get the above mentioned error.因此,当我尝试使用 utest 进行测试时,出现上述错误。 Please help.请帮忙。

PS - I am completely new to Scala and ScalaJs. PS - 我对 Scala 和 ScalaJs 完全陌生。

Well, the error doesn't appear to have anything to do with bodyFrag .好吧,该错误似乎与bodyFrag (Or Play, or even Scala.js, really.) The error is literally saying that getElementById("bodyContent") is null, which means it doesn't yet exist. (或者 Play,甚至 Scala.js,真的。)这个错误实际上是说getElementById("bodyContent")为 null,这意味着它还不存在。 I assume it's declared in the HTML.我假设它是在 HTML 中声明的。

This is a common trap in browser code.这是浏览器代码中的常见陷阱。 You need to wait for the DOM to be ready before you try manipulating it;在尝试操作 DOM 之前,您需要等待 DOM 准备就绪; you don't show the HTML page, so I'm not sure whether you're doing that, but I suspect not.你不显示 HTML 页面,所以我不确定你是否在这样做,但我怀疑不是。

There are various ways to wait for DOM ready -- the common (but slower) onload approach, and the jQuery approach, are discussed in the jQuery documentation .有多种等待 DOM 就绪的方法——常见(但较慢)的onload方法和 jQuery 方法在 jQuery 文档中进行了讨论。 As a quick fix, I would recommend wrapping the call to your Scala.js code inside window.onload .作为快速修复,我建议将调用包装到window.onload内的 Scala.js 代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM