
- Cypress 教程
- Cypress - 首頁
- Cypress - 簡介
- Cypress - 架構和環境設定
- Cypress - 測試執行器
- Cypress - 構建第一個測試
- Cypress - 支援的瀏覽器
- Cypress - 基本命令
- Cypress - 變數
- Cypress - 別名
- Cypress - 定位器
- Cypress - 斷言
- Cypress - 文字驗證
- Cypress - 非同步行為
- Cypress - 使用 XHR
- Cypress - jQuery
- Cypress - 複選框
- Cypress - 標籤頁
- Cypress - 下拉選單
- Cypress - 警報
- Cypress - 子視窗
- Cypress - 隱藏元素
- Cypress - 框架
- Cypress - 網頁表格
- Cypress - 滑鼠操作
- Cypress - Cookie
- Cypress - 獲取和釋出
- Cypress - 檔案上傳
- Cypress - 資料驅動測試
- Cypress - 提示彈出視窗
- Cypress - 儀表盤
- Cypress - 螢幕截圖和影片
- Cypress - 除錯
- Cypress - 自定義命令
- Cypress - Fixture
- Cypress - 環境變數
- Cypress - Hook
- Cypress - JSON 檔案配置
- Cypress - 報告
- Cypress - 外掛
- Cypress - GitHub
- Cypress 有用資源
- Cypress - 快速指南
- Cypress - 有用資源
- Cypress - 討論
Cypress - 自定義命令
Cypress 自定義命令是由使用者描述的,而不是 Cypress 的預設命令。這些自定義命令用於建立在自動化流程中重複的測試步驟。
我們可以新增和覆蓋已經存在的命令。它們應該放置在 Cypress 專案的 support 資料夾中的 commands.js 檔案中。

語法
Cypress 中自定義命令的語法如下:
Cypress.Commands.add(function-name, func) Cypress.Commands.add(function-name, opts, func) Cypress.Commands.overwrite(function-name, func)
這裡,
function-name 是正在新增/覆蓋的命令。
func 是傳遞給命令的引數的函式。
opts 用於傳遞一個選項來描述自定義命令的隱式特性。它也用於確定如何處理先前產生的主題(僅適用於 Cypress.Commands.add())並且選項的預設值為 false。選項 prevSubject 接受 false 以忽略先前的主題,接受 true 以接受先前的主題,並接受 optional 以啟動鏈或使用預先存在的鏈。選項接受字串、陣列或布林值。
自定義命令的實現
以下是 commands.js 中自定義命令的實現:
Cypress.Commands.add("userInput", (searchTxt) => { //to input search text in Google and perform search cy.get("input[type='text']").type(searchTxt); cy.contains("Google Search").click(); });
實際測試的實現
以下是使用自定義命令在 Cypress 中實現實際測試的示例:
describe('Tutorialspoint Test', function () { // test case it('Test Case 6', function (){ // launch the application cy.visit("https://www.google.com/"); //custom parent command cy.userInput('Java') }); });
執行結果
輸出如下:

輸出日誌顯示了自定義命令 – userInput(包含 get、type 和 click 命令)正在執行。
建議自定義命令不要太長。它應該簡短,因為在自定義命令中新增過多的操作會導致執行顯示。
廣告