将Angular添加到window类型定义

3
我正在进行Cypress的设置和运行。我希望Cypress能够直接调用我的一些函数来检查它们的输出。
但是,我似乎无法在我的测试中获取对Angular的引用。我看到了一些关于将自定义的“angular”属性添加到全局window对象的信息,但我仍然无法弄清楚如何做到这一点。

https://github.com/cypress-io/cypress/issues/3068#issuecomment-454109519

根据上面的例子,我该如何创建一个自定义属性,以便在 Cypress 中获取 Angular 对象?
1个回答

3
cypress/support中创建一个index.d.ts文件,其中包含以下内容(例如添加一个名为ng的属性):
interface Window {
  ng: {
    probe: typeof import("@angular/platform-browser/src/dom/debug/ng_probe").inspectNativeElement
    // // un-comment if you need these for some reason:
    // ɵcompilerFacade: import("@angular/compiler/src/jit_compiler_facade").CompilerFacadeImpl
    // coreTokens: {
    //   ApplicationRef: import("@angular/core").ApplicationRef
    //   NgZone: import("@angular/core").NgZone
    // }
  }
}

那么您应该能够使用:

cy.get('.some-ng-element').then(($el) => {
  const el = $el[0]  // get the DOM element from the jquery element
  const win = el.ownerDocument.defaultView // get the window from the DOM element
  const component = win.ng.probe(el).componentInstance
})

嗯...不起作用。我甚至尝试仅记录 win.ng,但它未定义。 - Justin Young
糟糕,忘记在ownerDocument后面加上.defaultView了,请告诉我这样是否有效。 - kuceb
@JustinYoung 为了获得更好的类型补全,可以查看扩展 Window 接口的更新代码。 - kuceb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接