I am a huge fan of the Cypress method .within()
for scoping commands to within a specific UI section. However, there may be times when you will want to escape out of this scope and then return to it and carry on with additional testing. Some examples I can think of are when a tooltip might appear over an element on hover, but be scoped outside of the related container in the DOM layout, or if you want to pick up a piece of data from a sibling element before carrying on with the test logic that you do want to be restricted in DOM scope.
I didn't know how to do this until recently, when such an instance came up, and I found this StackOverflow thread with the answer. I'm sharing it here as a blog post in case it helps someone else. All credit to Richard Matsen whose code I am stealing here:
"cy.document().its('body')
will give you a subject that is outside the .within()
, and it seems to go back to inner scope after (still within callback)."
cy.get('body').find('div.without'); // checking this query first (outer scope)
cy.get('div.myform').within(() => {
cy.contains('text within'); // inner scope
cy.document().its('body').find('div.without'); // outer scope
cy.contains('text within'); // inner scope
})
There are often scenarios where you can avoid needing to do this, but for the cases where it's unavoidable, this is a great trick to have up your sleeve.
Top comments (0)