Cypress: Temporarily escape from a cy.within()

Created on 6 Mar 2020  ·  3Comments  ·  Source: cypress-io/cypress

Current behavior:

cy.within() correctly scopes inner cy.get() and cy.root() calls.

Desired behavior:

However, I sometimes need to temporarily escape from the cy.within() scope.

This is especially true for commands. I need a command that searches the whole <body> even when it is called from inside a cy.within().

pkdriver proposal 💡 enhancement

Most helpful comment

I'm in the same situation as OP.

I have a custom command cy.modal(fn) which asserts that a modal was opened and scopes every query in fn to that modal. However, sometimes I need to escape the scope for a single query - when a piece of UI (dropdowns, datepickers, etc) if being rendered outside of the modal and placed on top.

cy.modal(() => {
    cy.get('button') // button inside the modal

    cy.dropdown(...) // this dropdown is inside of the modal but the "popup" is being rendered at the end of <body>
})

All 3 comments

I'm in the same situation as OP.

I have a custom command cy.modal(fn) which asserts that a modal was opened and scopes every query in fn to that modal. However, sometimes I need to escape the scope for a single query - when a piece of UI (dropdowns, datepickers, etc) if being rendered outside of the modal and placed on top.

cy.modal(() => {
    cy.get('button') // button inside the modal

    cy.dropdown(...) // this dropdown is inside of the modal but the "popup" is being rendered at the end of <body>
})

Would also like this enhancement––when working with Vue.js, v-select components the select modal that lists options appears outside the scope of the form that the component is in.

You can do this today by using cy.wrap() to wrap an element found using Cypress.$() which will traverse the entire document (outside of the scope of the within).

index.html

<html>
<body>
  <div id="modal">
    <p>My Modal</p>
    <button>close</button>
  </div>
  <a href="" class="my-link">This anchor outside the modal</a>
</body>
</html>

spec.js

it('get element outside of within', () => {
  cy.visit('index.html')
  cy.get('#modal').within(() => {
    // get element within modal
    cy.get('p').should('contain', 'My Modal')

    // cy.get('a').should('have.class', 'my-link') // won't work!
    // this anchor is outside of the modal!
    cy.wrap(Cypress.$('a')).should('have.class', 'my-link')

    // get element within modal
    cy.get('button').should('contain', 'close')
  })
})

Screen Shot 2020-11-19 at 12 48 29 PM

Closing as resolved with the above workaround.

If you're experiencing a bug similar to this in Cypress, please open a new issue with a fully reproducible example that we can run. There may be a specific edge case with the issue that we need more detail to fix.

Was this page helpful?
0 / 5 - 0 ratings