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")
   })
})

執行結果

輸出如下:

Cypress Hooks

輸出日誌顯示第一個執行的步驟是 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")
   })
})

執行結果

輸出如下:

Cypress Has Tags

輸出日誌顯示只有帶有 .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")
   })
})

執行結果

輸出如下:

Cypress Skip Tags

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

廣告