Cypress web自动化39-.trigger()常用鼠标操作事件

前言

在web页面上经常遇到的鼠标事件有:鼠标悬停操作,鼠标右键,鼠标长按,拖拽等操作

trigger()

trigger 方法用于在 DOM 元素上触发事件

语法使用示例

.trigger(eventName)
.trigger(eventName, position)
.trigger(eventName, options)
.trigger(eventName, x, y)
.trigger(eventName, position, options)
.trigger(eventName, x, y, options)

正确用法

cy.get('a').trigger('mousedown') // 触发 mousedown 事件

不正确的用法

cy.trigger('touchstart')             // 错误,不能直接用在cy.
cy.location().trigger('mouseleave')  // 错误, 'location' 不生成 DOM 元素

要求:.trigger() 需要链接到产生 DOM 元素的命令。

参数说明

eventName(字符串)

event 在DOM元素上要触发的的名称。

position(字符串)

应该触发事件的位置。该center位置是默认位置。有效的位置topLeft,top,topRight,left,center,right,bottomLeft,bottom,和bottomRight。

x(数字)

从元素左侧到触发事件的距离(以像素为单位)。

y (数字)

从元素顶部到触发事件的距离(以像素为单位)。

options

传递选项对象以更改的默认行为.trigger()。

选项 默认 描述
log true 在命令日志中显示命令
force false 强制执行操作,禁用等待操作性
bubbles true 事件是否起泡
cancelable true 活动是否可取消
timeout defaultCommandTimeout 等待超时.trigger()之前解决的时间

您还可以任意事件属性(例如clientX,shiftKey),他们会被附加到事件。传递坐标参数(clientX,pageX等)将覆盖位置坐标。

鼠标事件

鼠标悬停操作

触发 mouseover 事件,鼠标悬停操作。在触发事件发生之前,DOM元素必须处于interactable(可交互)状态(它必须可见并且不能禁用)

cy.get('button').trigger('mouseover') // yields 'button'

鼠标长按操作

先触发 mousedown 按下鼠标,wait等待事件,再 mouseleave 释放鼠标

cy.get('.target').trigger('mousedown')
cy.wait(1000)
cy.get('.target').trigger('mouseleave')

特殊的 mousedown 事件

// Main button pressed (usually the left button)
cy.get('.target').trigger('mousedown', { button: 0 })
// Auxiliary button pressed (usually the middle button)
cy.get('.target').trigger('mousedown', { button: 1 })
//Secondary button pressed (usually the right button)
cy.get('.target').trigger('mousedown', { button: 2 })

拖拽 drag and drop

要使用jQuery UI sortable模拟拖放,需要pageX和pageY属性以及 which:1

cy.get('[data-cy=draggable]')
  .trigger('mousedown', { which: 1, pageX: 600, pageY: 100 })
  .trigger('mousemove', { which: 1, pageX: 600, pageY: 600 })
  .trigger('mouseup')

参考案例:https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/testing-dom__drag-drop

触发位置

触发mousedown按钮右上方的

cy.get('button').trigger('mousedown', 'topRight')

指定相对于左上角的明确坐标

cy.get('button').trigger('mouseup', 15, 40)

鼠标悬停案例

案例:百度-设置-(鼠标悬停弹出选项)搜索设置

/**
 * Created by dell on 2020/6/9.
 * 作者:上海-悠悠 交流QQ群:939110556
 */

describe('baidu setting', function() {

    before( function() {
        cy.visit("https://www.baidu.com/")
    })


    it('mouseover event', () => {

        // 鼠标悬停 mouseover
        cy.get("#s-usersetting-top").trigger('mouseover')
        cy.contains("搜索设置")
            // 判断设置选项可见
            .should('be.visible')
            .click()

    })
 })

trigger 更多介绍文档https://docs.cypress.io/api/commands/trigger.html

原文地址:https://www.cnblogs.com/yoyoketang/p/13087859.html