Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How to break out of .within() scope in Cypress
Sam E. Lawrence
Sam E. Lawrence

Posted on

     

How to break out of .within() scope in Cypress

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 foundthis StackOverflow thread with the answer. I'm sharing it here as a blog post in case it helps someone else. All credit toRichard 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})
Enter fullscreen modeExit fullscreen mode

There are often scenarios where you can avoidneeding to do this, but for the cases where it's unavoidable, this is a great trick to have up your sleeve.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi, I'm Sam and I'm an advocate for quality software. I'm a Cypress Ambassador and I work as the QA Lead at Pointivo where we're digitizing real-world infrastructure for analysis and maintenance.
  • Location
    ATL
  • Education
    Georgia Tech
  • Pronouns
    He/him/his
  • Work
    QA Lead @ Pointivo
  • Joined

More fromSam E. Lawrence

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp