
- 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 - 鉤子
- Cypress - JSON 檔案配置
- Cypress - 報告
- Cypress - 外掛
- Cypress - GitHub
- Cypress 有用資源
- Cypress - 快速指南
- Cypress - 有用資源
- Cypress - 討論
Cypress - 鉤子
Cypress 鉤子用於在每個測試之前/之後執行某些操作。一些常見的鉤子如下:
before - 在 describe 塊中任何測試執行之前執行一次。
after - 在 describe 塊中所有測試執行之後執行一次。
beforeEach - 在 describe 塊中每個 it 塊執行之前執行。
afterEach - 在 describe 塊中每個 it 塊執行之後執行。
實現
Cypress 鉤子命令的實現如下:
describe('Tutorialspoint', function() { before(function() { // executes once prior all tests in it block cy.log("Before hook") }) after(function() { // executes once post all tests in it block cy.log("After hook") }) beforeEach(function() { // executes prior each test within it block cy.log("BeforeEach hook") }) afterEach(function() { // executes post each test within it block cy.log("AfterEac hook") }) it('First Test', function() { cy.log("First Test") }) it('Second Test', function() { cy.log("Second Test") }) })
執行結果
輸出如下:

輸出日誌顯示第一個執行的步驟是 BEFORE ALL。
最後一個執行的步驟是 AFTER ALL。兩者都只運行了一次。
BEFORE EACH 下執行的步驟運行了兩次(每個 TEST BODY 之前)。
同樣,AFTER EACH 下執行的步驟運行了兩次(每個 TEST BODY 之後)。
兩個 it 塊按其實現順序執行。
標籤
除了鉤子,Cypress 還有標籤 -.only 和 .skip。
.only 標籤用於執行其標記的 it 塊,.skip 標籤用於排除其標記的 it 塊。
使用 .only 的實現
.only 標籤在 Cypress 中的實現如下:
describe('Tutorialspoint', function() //it block with tag .only it.only('First Test', function() { cy.log("First Test") }) //it block with tag .only It.only('Second Test', function() { cy.log("Second Test") }) it('Third Test', function() { cy.log("Third Test") }) })
執行結果
輸出如下:

輸出日誌顯示只有帶有 .only 標籤的 it 塊(第一個和第二個測試)被執行。
使用 .skip 的實現
.skip 標籤在 Cypress 中的實現如下:
describe('Tutorialspoint', function() it('First Test', function() { cy.log("First Test") }) it('Second Test', function() { cy.log("Second Test") }) //it block with tag .skip it.skip('Third Test', function() { cy.log("Third Test") }) })
執行結果
輸出如下:

輸出日誌顯示帶有 .skip 標籤的 it 塊(第三個測試)被跳過執行。
廣告