Home > front end >  How to test relative positioning of elements in cypress?
How to test relative positioning of elements in cypress?

Time:03-03

I am currently new to cypress and wants to test that Forgot Password should be below Login button in Facebook page? Is there a way to do that? Facebook page

Is there a way to test relative positioning of elements in cypress?

CodePudding user response:

I think you can use jQuery .position()

cy.get('#element1')
  .then($el => $el.position().top)  // get 1st top value
  .then(top1 => {
    cy.get('#element2')
      .then($el => $el.position().top)  // get 2nd top value
      .then(top2 => {
        expect(top1).to.be.gt(top2)
      })
  })

Notes

Cypress use jQuery to find elements. Chaining .then($el => ... exposes the jQuery object containing the element, so now you can apply other jQuery functions that are not part of the Cypress commands.

In fact, any other Javascript functions you want.

You can also make reusable functions

const getTop = ($el) = $el.position().top;

cy.get('#element1').then(getTop)  
  .then(top1 => {
    cy.get('#element2').then(getTop)
      .then(top2 => {
        expect(top1).to.be.gt(top2)
      })
  })

CodePudding user response:

You can use the cypress method next() to determine the element next to Log in button like this. next() gets the immediately following sibling of each DOM element within a set of DOM elements.

cy.get('div[type="submit"]').next().should('have.text', 'Forgot password?')
  • Related