- 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 - Get 和 Post
- Cypress - 檔案上傳
- Cypress - 資料驅動測試
- Cypress - 提示彈出視窗
- Cypress - 儀表盤
- Cypress - 截圖和影片
- Cypress - 除錯
- Cypress - 自定義命令
- Cypress - Fixture
- Cypress - 環境變數
- Cypress - Hook
- Cypress - JSON 檔案配置
- Cypress - 報告
- Cypress - 外掛
- Cypress - GitHub
- Cypress 有用資源
- Cypress - 快速指南
- Cypress - 有用資源
- Cypress - 討論
Cypress - jQuery
Cypress 可以作用於 jQuery 物件及其方法以及其內部命令。雖然 Cypress 使用 get 方法來識別網頁元素,但 jQuery 使用 $() 方法來達到相同目的。
在 Cypress 中,識別網頁元素的命令如下:
cy.get('h1#heading')
而在 jQuery 中,識別網頁元素的命令如下:
$('h1#heading')
Cypress 基於 JavaScript,其本質是非同步的。但是,Cypress 命令透過內部解析 Promise 來表現得像同步一樣,對終端使用者隱藏了這一過程。
然而,當 Cypress 作用於 jQuery 物件及其方法時,必須專門實現 Promise 邏輯,以使流程同步(藉助 then 方法)。
例如,當我們想要提取網頁元素的文字內容(使用 jQuery 方法 - text)時,我們需要使用 then 方法實現 Promise。
jQuery 中的 Promise 實現
以下是 jQuery 中 Cypress Promise 實現的命令:
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://#")
// Promise implementation with then()
cy.get('h1#headingText').find('span').then(function(e){
//method text to obtain text content
const t = e.text()
expect(t).to.contains('Sign')
})
})
})
在 jQuery 中,如果提供的定位器與 DOM 中的任何網頁元素都不匹配,則會返回一個空集合。
為了避免異常,建議驗證 $() 生成的 jQuery 集合的長度。相應的命令如下:
const e = $('#txt')
if (e.length > 0){
//proceed
}
但是,如果 DOM 中沒有匹配的網頁元素,Cypress 會自動進入重試模式,直到元素可用或超時,如下所示:
cy.get('#txt')
.then((e) => { //proceed working on element })
該方法生成一個 Promise。此外,只有當網頁元素與定位器匹配時,Promise 才會處於已解析狀態。如果 Promise 處於拒絕狀態,則 then 塊中的邏輯永遠不會執行。
我們可以使用以下表達式訪問 Cypress 中的 jQuery 方法:
Cypress.$( '#txt'), where #txt is the locator.
jQuery 方法的實現
下面是使用 jQuery 在 Cypress 中識別和執行測試的命令:
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://#")
// access web element with Cypress.$
cy.request('/').get('h1#headingText').then(function(e){
Cypress.$(e).find('span')
const t = e.text()
cy.log(t)
})
})
})
當執行上述測試時,如果我們開啟控制檯(按 F12),並使用表示式 Cypress.$('h1#headingText').text() 查詢所需的網頁元素,我們可以驗證我們的測試,如下所示:
日誌訊息“Sign –in”來自 Cypress 中的 cy.log 命令。