前言
Cypress 提供了 hooks 函数,方便我们在组织测试用例的时候,设置用例的前置操作和后置清理。
类似于 python 的 unittest 里面的 setUp 和 setUpclass 功能
Hooks
Cypress 提供了 hooks 函数。
这些有助于设置要在一组测试之前或每个测试之前运行的条件。它们也有助于在一组测试之后或每次测试之后清理条件。
1describe('Hooks', () => { 2 before(() => { 3 // runs once before all tests in the block 4 }) 5 6 after(() => { 7 // runs once after all tests in the block 8 }) 9 10 beforeEach(() => { 11 // runs before each test in the block 12 }) 13 14 afterEach(() => { 15 // runs after each test in the block 16 }) 17})
Hooks 和测试执行的顺序如下:
- before()钩子运行(一次)
- beforeEach() 每个测试用例前都会运行
- it 运行测试用例
- afterEach() 每个测试用例之后都会运行
- after() 钩子运行(一次)
执行案例
写2个测试用例,带上 hooks 函数,查看用例执行顺序,
1/** 2 * Created by dell on 2020/5/13. 3 * hook_demo.js 4 * 作者:上海-悠悠 5 */ 6 7 8describe('Hooks', () => { 9 before(() => { 10 // runs once before all tests in the block 11 cy.log("所有的用例之前只执行一次,测试准备工作") 12 }) 13 after(() => { 14 // runs once after all tests in the block 15 cy.log("所有的用例之后只执行一次") 16 }) 17 beforeEach(() => { 18 // runs before each test in the block 19 cy.log("每个用例之前都会执行") 20 }) 21 afterEach(() => { 22 // runs after each test in the block 23 cy.log("每个用例之后都会执行") 24 }) 25 it('test case 1', () => { 26 cy.log("test case 1") 27 expect(true).to.eq(true) 28 }) 29 it('test case 2', () => { 30 cy.log("test case 2") 31 expect(true).to.eq(true) 32 }) 33})
运行结果
