Cypress学习15-Hooks使用方法

前言

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
 * 作者:上海-悠悠 
 */


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

运行结果

相关文章

本文技术难度★★★,如果前编内容顺利执行,请继续。如果Se...
如果想从头学起Cypress,可以看下面的系列文章哦https://www...
web技术已经进化了,web的测试技术最终还是跟上了脚步,新一...
不很久不很久以前据说某家公司有两位前端,天天撸bug,为啥嘞...
我刚开始学习JavaScript并且一直在使用赛普拉斯来自动化一些...
cypress在pycharm中编写首先打开pycharm,打开cypress项目 ...