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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM