如何在名称中使用"."定义全局作用域方法



我正在尝试为 : https://facebook.github.io/jest/docs/en/api.html#testonlyname-fn 定义外观

@JSGlobalScope
@js.native
object JestGlobal extends js.Object {
  def test(str: String, function: js.Function0[_]): Unit = js.native
  @JSName("test.only")
  def testOnly(str: String, function: js.Function0[_]): Unit = js.native
  def expect[T](in:T) : Matcher[T] = js.native
}
@js.native
trait Matcher[T] extends js.Object {
  def toBe(in:T):Unit = js.native
}

调用名称无效的全局作用域的方法 不允许使用 JavaScript 标识符。[错误] 看 https://www.scala-js.org/doc/interoperability/global-scope.html 更多信息。

编辑:(答案(

 def test : JestTestObject = js.native
@js.native
trait JestTestObject extends js.Object {
  def only(str: String, function: js.Function0[_]): Unit = js.native
}

出于所有实际目的,没有名称为 test.only 的 JS 函数这样的东西。更有可能的是,有一个顶级对象,其名称为 test ,并且它有一个名为 only 的方法。您可以将其建模为:

@js.native
@JSGlobal("test")
object JestTest extends js.Object {
  def only(str: String, function: js.Function0[_]): Unit = js.native
}

您还可以使用相同的对象来表示名称为 test 的顶级函数(因为显然库是这样呈现的(,方法是添加一个 apply 方法:

@js.native
@JSGlobal("test")
object JestTest extends js.Object {
  // This is the test(...) function
  def apply(str: String, function: js.Function0[_]): Unit = js.native
  // This is the test.only(...) function
  def only(str: String, function: js.Function0[_]): Unit = js.native
}

您的变体作为自我答案也是有效的,但可以使其更惯用,如下所示:

@js.native
@JSGlobalScope
object JestGlobal extends js.Object {
  @js.native
  object test extends js.Object {
    // This is the test(...) function
    def apply(str: String, function: js.Function0[_]): Unit = js.native
    // This is the test.only(...) function
    def only(str: String, function: js.Function0[_]): Unit = js.native
  }
  def expect[T](in: T): Matcher[T] = js.native
}

最新更新