Justin Young
Justin Young

Reputation: 2463

Add angular to window type definition

I'm in the process of getting Cypress up and running. I'd like to have Cypress directly call some of my functions to check their output.

I can't seem to get a reference to angular though within my test. I saw some info about adding a custom "angular" property to the global window object but I still can't seem to figure it out.

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

Based on the example above, how would I create a custom property so that I can get ahold of the angular object within Cypress?

Upvotes: 3

Views: 531

Answers (1)

kuceb
kuceb

Reputation: 18063

Create an index.d.ts in cypress/support with the following (to add a property called ng for example):

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

Then you should be able to use:

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

Upvotes: 3

Related Questions