如何在 Cypress 中實現鉤子?


我們可以在 Cypress 中實現鉤子。Cypress 鉤子用於在每一個測試中/測試前後執行某些操作。一些常見的鉤子有:

  • before –在 describe 塊中執行任何測試前執行一次。

  • after –在 describe 塊中執行所有測試後執行一次。

  • beforeEach –在 describe 塊中執行每個 it 塊前執行。

  • afterEach –在 describe 塊中執行每個 it 塊後執行。

示例

實現

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 塊按照實現順序執行。

更新於: 2021-11-19

473 次瀏覽

開啟你的 職業生涯

完成課程來獲得認證

開始
廣告