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 块(第三个测试)被跳过执行。

广告
© . All rights reserved.