Cannot assert element is an HTMLDivElement

Viewed 26

I want to check the type of element found with an id. I'm using an asserton with instanceof matcher, but it's failing.

My test is as follows:

cy.get('#calculated').should(($el) => {
  expect($el[0]).to.be.instanceof(HTMLDivElement)
})

My HTML is

<div id="calculated">123.40</div>

Clearly the element is a div, so what is wrong with the assertion syntax?

1 Answers

The instanceof element depends internally on the window that creates the element.

When you use the following, you are using HTMLDivElement from the top-level window (the Cypress runner window).

expect($el[0]).to.be.instanceof(HTMLDivElement)

But the element you are testing is created by the window inside the app iframe.

If you reference HTMLDivElement from that window, the assertion will pass

cy.window().then(win => {      // app window

  cy.get('#calculated').should(($el) => {
    expect($el[0]).to.be.instanceof(win.HTMLDivElement)  // qualify the type with
                                                         // the window reference
  })
})
Related