Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress assert contextmenu preventDefault true

Tags:

cypress

I'm trying to test that the context menu does not show when a user right clicks.

I've got cy.getByTestId('element-to-click').rightclick();

When I click on rightclick and see the Command output, I see is has an array of Mouse Events, one of them is Event Type: 'contextmenu' and has Prevented Default: true.

command output

I don't know how to assert in Cypress that contextmenu has Prevented Default set to true.

like image 965
Jrow Avatar asked Nov 18 '25 21:11

Jrow


1 Answers

I don't know why testing around events is so hard, but reverse-engineering the Cypress console table I came up with this.

const getClickEvents = (subject) => {
  const { mouse } = cy.devices
  const coords = Cypress.dom.getElementCoordinatesByPosition(subject)
  const clickEvents = mouse.click(coords.fromElViewport, subject[0])
  return clickEvents
}

cy.get('button#1')
  .then(getClickEvents)
  .should(clickEvents => {
    expect(clickEvents.click.preventedDefault).to.eq(true)  // passes
  })

cy.get('button#2')
  .then(getClickEvents)
  .should(clickEvents => {
    expect(clickEvents.click.preventedDefault).to.eq(false)  // passes
  })

where clickEvents is data for the whole table as shown in your question, so you can easily pick out properties to assert.

like image 152
Fody Avatar answered Nov 21 '25 15:11

Fody