Can we use Cypress to assert that a button is actionable without clicking it

Viewed 287

Cypress 'click' command actually asserts a lot of things behind the scene (e.g. visible, enable, not covered). Is there a function to asserts all these things without actually clicking a button?

My use case is that when clicking the button, it will redirect to an external website so I don't want to actually click it.

1 Answers

Deal with window replace shows a method to stub the redirect.

If you can use it depends on how your redirect happens. There's a couple more ways I know of, they can also be stubbed.

it('replaces', () => {
  cy.on('window:before:load', (win) => {
    win.__location = {
      replace: cy.stub().as('replace')
    }
  })

  cy.intercept('GET', 'index.html', (req) => {
    req.continue(res => {
      res.body = res.body.replaceAll(
        'window.location.replace', 'window.__location.replace')
    })
  }).as('index')

  cy.visit('index.html')
  cy.wait('@index')
  cy.contains('h1', 'First page')
  cy.get('@replace').should('have.been.calledOnceWith', 'https://www.cypress.io')
})
  • a fake window.location is created with a stub on replace() function
  • the the page is intercepted as it loads and the stub is installed
  • the click event calling the stub can be verified without actually redirecting
Related