Cyprerss的钩子函数

65 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第4天,点击查看活动详情

大家好,我是阿萨。昨天学习了如何使用describe,context,specify 和it 去组织自动化测试用例。大家也学会了如何去写好一个test suites了。

有同学就问了,之前用selenium 或者其他测试框架的时候,都有setup 和teardown 等函数。cypress 咋没见这2个函数。哪如何实现每个测试的suite 之前都执行某个代码逻辑或者是每个测试用例之前都需要执行代码?

今天我们就来学习下cypress的 钩子函数。

Cypress 和Mocha 一样提供四个钩子函数:

  • before() ----当前测试套件,所有测试用例之前执行。

  • after()---当前测试套件,所有测试用例之后执行。

  • beforeeach()----当前测试套件,每个测试用例之前执行。

  • aftereach()-----当前测试套件,每个测试用例之后执行。

它们的作用是测试开始时设置测试的先决条件(比如准备测试数据)。或者测试结束后对测试环境进行清理(例如清理DB)。使用个例子看一下。

describe('1st Describe to show 1st suite ', () => {
    before(function(){        
    cy.log("Will run before all test scripts.")    
    }    
    )
    
    beforeEach(function(){        
    cy.log("Will run before each testing scripts.")    
    }
    )
    
    afterEach(function(){        
    cy.log("Will run after each testing scripts.")    
    }
    )
    
describe('Describe Inside Describe to show nested suite', () => {
    it('first test inside', () => {            
    cy.log('first test inside')            
    assert.equal(true, true)        
    })   
    })    
    
    it('1st test', () => {
        cy.log('1st test')        
        assert.equal(true, true)    
        })    
        
     specify('2nd test', () => {        
     cy.log('2nd test')        
     assert.equal(true, true)    
     })      
     
     after(function(){        
     cy.log("Will run after all test scripts.") 
     })
     })
     
context('2nd suite', () => {
    it('first test', () => {        
    cy.log('first test')        
    assert.equal(true, true) 
    })    
    
    it('2nd test', () => {
    cy.log('2nd test')
    assert.equal(true, true)
    })
})

这是例子的执行结果,通过例子的执行结果可以清晰的看出作用域。

Image

Image

你学会了吗?

如果觉得阿萨的内容对你有帮助,欢迎围观点赞。