
- 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 - 固定裝置
- Cypress - 環境變數
- Cypress - 鉤子
- Cypress - JSON 檔案配置
- Cypress - 報告
- Cypress - 外掛
- Cypress - GitHub
- Cypress 有用資源
- Cypress - 快速指南
- Cypress - 有用資源
- Cypress - 討論
Cypress - 斷言
Cypress 有多種斷言型別,這些斷言來自不同的庫,例如 Mocha、Chai 等。斷言型別分為顯式和隱式。
隱式斷言
如果斷言適用於從鏈中父命令獲得的物件,則稱為隱式斷言。常見的隱式斷言包括 .and/.should。
這些命令不能單獨使用。通常,當我們需要驗證特定物件上的多個檢查時,會使用它們。
讓我們透過以下示例來說明隱式斷言:
// test suite describe('Tutorialspoint', function () { it('Scenario 1', function (){ // test step to launch a URL cy.visit("https://tutorialspoint.tw/videotutorials/index.php") // assertion to validate count of sub-elements and class attribute value cy.get('.toc chapters').find('li').should('have.length',5) .and('have.class', 'dropdown') }); });
執行結果
輸出如下:

輸出日誌顯示了使用 should 和命令獲得的兩個斷言。
顯式斷言
如果斷言直接適用於物件,則稱為顯式斷言。常見的顯式斷言包括 assert/expect。
顯式斷言的命令如下:
// test suite describe('Tutorialspoint', function () { // it function to identify test it('Scenario 1', function (){ // test step to launch a URL cy.visit("https://#") // identify element cy.get('h1#headingText').find('span').then(function(e){ const t = e.text() // assertion expect expect(t).to.contains('Sign') }) }) })
執行結果
輸出如下:

輸出日誌顯示了使用 expect 命令直接應用於物件的斷言。
Cypress 具有預設斷言,這些斷言在內部處理,不需要專門呼叫。
一些示例如下:
cy.visit () - 預期頁面顯示內容且狀態碼為 200。
cy.request () - 預期遠端伺服器可用併發送響應。
cy.contains () - 預期帶有其屬性的網頁元素在 DOM 中可用。
cy.get () - 預期網頁元素在 DOM 中可用。
.find () - 預期網頁元素在 DOM 中可用。
.type () - 預期網頁元素變為可輸入狀態。
.click () - 預期網頁元素變為可點選狀態。
.its () - 預期在現有主題上獲取網頁元素屬性。
其他 Cypress 斷言
其他 Cypress 斷言如下:
length
它檢查從先前鏈式命令獲得的元素數量。
例如,
cy.get('#txt-fld').should('have.length',5)
value
它檢查網頁元素是否具有特定值。
例如,
cy.get('#txt-fld').should('have.length',5)
value
它檢查網頁元素是否具有特定值。
例如,
cy.get(' #txt-fld').should('have.value', 'Cypress')
class
它檢查網頁元素是否具有特定類。
例如,
cy.get('#txt-fld'').should('have.class', 'txt')
contain
它檢查網頁元素是否包含特定文字。
例如,
cy.get('#txt-fld'').should('contain', 'Cypress')
visible
它檢查網頁元素是否可見。
例如,
cy.get('#txt-fld'').should('be.visible')
exist
它檢查網頁元素是否在文件物件模型 (DOM) 中可用。
例如,
cy.get('#txt-fld'').should('not.exist');
css
它檢查網頁元素是否具有特定 css 屬性。
例如,
cy.get('#txt-fld'').should('have.css', 'display', 'block');
廣告