https://cypress.io logo
window.Cypress is undefined from the app code, but...
# i-need-help
e
I'm working on automated testing of a React/Next application. One of the pages has some logic in a
useEffect()
and then does a
window.open()
passing
_blank
as it's second argument like
window.open(url, "_blank")
which causes it to open in a new tab. While running inside Cypress I want to change this to
_self
so I can test the URL was properly navigated to. At the top of the
useEffect()
I'm setting a variable for this using
const openLocation = window.Cypress ? '_self' : '_blank';
and then passing
openLocation
to the
window.open()
call. The problem I'm running into is
openLocation
is always
_blank
even though when I'm running cypress I can go to the console and do
window.Cypress
and see there is a Cypress object defined there. Is this some sort of race condition?
In my spec file this doesn't pass either, even with a long global timeout:
cy.window().its('Cypress').should('be.an', 'object')
I found that I needed to use
window.parent.Cypress
. Not quite sure why...
In summary I changed it to this in the application code:
const openLocation = window.parent.Cypress ? '_self' : '_blank';
And this also passes in the spec as a sanity check:
cy.window().its('parent.Cypress').should('be.an', 'object')
And according to the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/API/Window/parent > The Window.parent property is a reference to the parent of the current window or subframe. > > If a window does not have a parent, its parent property is a reference to itself. Since
parent
references
window
if there's no
parent
, this seems like a safe solution.