前言
Cypress 提供了 hooks 函數,方便我們在組織測試用例的時候,設置用例的前置操作和后置清理。
類似於 python 的 unittest 里面的 setUp 和 setUpclass 功能
Hooks
Cypress 提供了 hooks 函數。
這些有助於設置要在一組測試之前或每個測試之前運行的條件。它們也有助於在一組測試之后或每次測試之后清理條件。
describe('Hooks', () => {
before(() => {
// runs once before all tests in the block
})
after(() => {
// runs once after all tests in the block
})
beforeEach(() => {
// runs before each test in the block
})
afterEach(() => {
// runs after each test in the block
})
})
Hooks 和測試執行的順序如下:
- before()鈎子運行(一次)
- beforeEach() 每個測試用例前都會運行
- it 運行測試用例
- afterEach() 每個測試用例之后都會運行
- after() 鈎子運行(一次)
執行案例
寫2個測試用例,帶上 hooks 函數,查看用例執行順序,
/**
* Created by dell on 2020/5/13.
* hook_demo.js
* 作者:上海-悠悠 QQ交流群:939110556
*/
describe('Hooks', () => {
before(() => {
// runs once before all tests in the block
cy.log("所有的用例之前只執行一次,測試准備工作")
})
after(() => {
// runs once after all tests in the block
cy.log("所有的用例之后只執行一次")
})
beforeEach(() => {
// runs before each test in the block
cy.log("每個用例之前都會執行")
})
afterEach(() => {
// runs after each test in the block
cy.log("每個用例之后都會執行")
})
it('test case 1', () => {
cy.log("test case 1")
expect(true).to.eq(true)
})
it('test case 2', () => {
cy.log("test case 2")
expect(true).to.eq(true)
})
})
運行結果
QQ交流群:939110556