Cypress Force a Click

Profile picture for user arilio666

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.