web自动化之trigger()常用鼠标操作事件

转载自品略图书馆 http://www.pinlue.com/article/2020/06/1614/5610751058447.html

 

前言

在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()。

选项默认描述
logtrue在命令日志中显示命令
forcefalse强制执行操作,禁用等待操作性
bubblestrue事件是否起泡
cancelabletrue活动是否可取消
timeoutdefaultCommandTimeout等待超时.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("[>  .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)

鼠标悬停案例

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

//describe("baidu setting", function() {    before( function() {        cy.visit("https://www.pinlue.com/")    })    it("mouseover event", () => {        // 鼠标悬停 mouseover        cy.get("#s-usersetting-top").trigger("mouseover")        cy.contains("搜索设置")            // 判断设置选项可见            .should("be.visible")            .click()    }) })

 

trigger 更多介绍文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值