Skip to main content

Cypress Force a Click

Today in this article, we will see how we can force a click. For that, let us first see a scenario where and when the force is used and effective.

First, we will see the pessimistic scenario where the test fails with the average click and the optimistic plan that works with force.

For this, we are going to use the intercept example. If you want to know what intercept in cypress does, learn what intercept is by clicking this https://www.programsbuzz.com/article/cypress-aliases-intercepted-routes

Negative scenario

describe('Intercepting Gorestapi',()=>{
    it('Visiting Gorestapi',()=>{
        cy.visit('https://gorest.co.in/')
        
    })
    it('Intercepting Route of users',()=>{
        cy.intercept({path : '/public/v2/users' }).as('aPIntercept')
        cy.get("table:nth-of-type(1) a[href = 'https://gorest.co.in/public/v2/users']").click()
        cy.wait('@aPIntercept').then(interception => {
            cy.log(JSON.stringify(interception))
            console.log(JSON.stringify(interception))
        })
    })
})

  • As we can see, the test failed as it could not click the element, and it says that another element covered it.
  • It even suggests we use force argument.
  • So, we can use force to make this work in this case.

Positive Scenario

describe('Intercepting Gorestapi',()=>{
    it('Visiting Gorestapi',()=>{
        cy.visit('https://gorest.co.in/')
        
    })
    it('Intercepting Route of users',()=>{
        cy.intercept({path : '/public/v2/users' }).as('aPIntercept')
        cy.get("table:nth-of-type(1) a[href = 'https://gorest.co.in/public/v2/users']").click({force: true})
        cy.wait('@aPIntercept').then(interception => {
            cy.log(JSON.stringify(interception))
            console.log(JSON.stringify(interception))
        })
    })
})

We can see how the test has passed when the force argument is passed into click with true. This is how we can implement the force click onto an element.

Tags
Submitted by arilio666 on February 10, 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.