- 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 - 鉤子
- Cypress - JSON 檔案配置
- Cypress - 報告
- Cypress - 外掛
- Cypress - GitHub
- Cypress 有用資源
- Cypress - 快速指南
- Cypress - 有用資源
- Cypress - 討論
Cypress - 非同步行為
Cypress 來源於 node.js,而 node.js 基於 JavaScript。Cypress 命令本質上是同步的,因為它們依賴於 node 伺服器。非同步流程意味著測試步驟的執行不依賴於其之前的步驟。
它們之間沒有依賴關係,每個步驟都作為一個獨立的實體執行。雖然測試步驟按順序排列,但單個測試步驟不會考慮前一步的結果,而只是執行自身。
示例
以下是 Cypress 中非同步行為的一個示例:
// test suite
describe('Tutorialspoint', function () {
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://#")
// identify element
cy.get('h1#headingText').find('span').should('have.text', 'Sign in')
cy.get('h1#headingText').find('span').then(function(e){
const t = e.text()
// get in Console
console.log(t)
})
// Console message
console.log("Tutorialspoint-Cypress")
})
})
執行結果
輸出如下:
Promise
右鍵點選測試執行器並點選“檢查”,我們可以在控制檯中驗證結果。這裡,Tutorialspoint-Cypress(之前的一個步驟)在Sign – in(之後新增的步驟)之前被記錄在控制檯中。
Cypress 命令的設計方式使得每個步驟都按順序執行,並且不會同時觸發。但是,它們是按順序排列的。因此,它使流程同步。這是透過 Promise 實現的。
在上面的例子中,console.log 是一個純 JavaScript 語句。它沒有像 Cypress 命令那樣排列和等待的能力。Promise 允許我們以序列模式執行 Cypress 命令。
Promise 中的模式
Promise 有三種模式來對命令執行的狀態進行分類。它們如下:
已解決(Resolved) - 如果測試步驟成功執行,則會產生此結果。
掛起(Pending) - 如果測試步驟執行結果正在等待,則為該結果。
已拒絕(Rejected) - 如果測試步驟執行失敗,則為該結果。
只有在先前的步驟成功執行或收到已解決的 Promise 響應後,Cypress 命令才會執行。然後,該方法用於在 Cypress 中實現 Promise。
示例
以下是 Cypress 中 Promise 的示例:
describe('Tutorialspoint Test', function () {
it('Promise', function (){
return cy.visit('https://#')
.then(() => {
return cy.get('h1#heading');
})
})
})
Cypress 對 Promise 的實現是封裝的,不可見。因此,它有助於編寫更簡潔的程式碼。此外,在自動化測試時,我們不必考慮 Promise 的狀態。
無 Promise 的實現
以下命令說明如何在 Cypress 中無需 Promise 進行實現:
describe('Tutorialspoint Test', function () {
it('Without Promise', function (){
cy.visit('https://#')
cy.get('h1#heading')
})
})