Skip to main content

Cypress root command

Cypress root command fetches the root DOM element. Which means this command is used to fetch the root element of a webpage from where the origin tag was created.

  • Simply put, it gets the root of a grown tree buried within the ground.
  • It can also be coupled mainly with the within command to yield its root.
  • By default, the root DOM element yielded by this command is <html>.
  • When calling .root() from a .within() command, the root element will point to the element you are "within".

Syntax

cy.root()
cy.root(options)

Some of the options we can include in the command can be a timeout, log, etc.

  • Log: To display the command in the command log.
  • Timeout: Wait for some particular thing to get finished before timing out.

Correct Use

cy.root() --> Yield root element <html>

cy.get('li').within(($li) => {
  cy.root() // Yield root element <li>
})

When inside within the root element will point out to the element we are "within."

Let us check out various root command examples.

Example 1: Using Plain cy.root()

Let us check out what cy.root() does when executing it plainly without using it within command.

In this article, we will be using the  https://www.programsbuzz.com/user/login login page for the root command.

it('Visit Page',() => {
    cy.visit("https://www.programsbuzz.com/user/login")
    cy.root()
}) 

As we can see, it has yielded <html> element.

Example 2: Using Assertion

it('Visit Page',() => {
    cy.visit("https://www.programsbuzz.com/user/login")
    cy.root().should('match', 'html')
}) 

As we can see, it has been asserted that the yielded element is HTML.

Example 3: Form Interaction With Root

it('Visit Page',() => {
    cy.visit("https://www.programsbuzz.com/user/login")
    
    cy.get('form#user-login-form').within(($form)=>{
        cy.get("input#edit-name").type('naruto')
        cy.get("input#edit-pass").type('shadowclone')
        cy.root().submit()
    })
}) 
  • We are first visiting the respective page.
  • Then we isolate a part of the form with the within command and create a parameter $form.
  • Now we are fetching the CSS selectors of the username and password field.
  • Using root now as it submits the form yielded from within.
  • Submit command is used in forms to submit within that form scope automatically.

We can see that root yields here from within command.

Tags
Submitted by arilio666 on January 11, 2022

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.