Cypress的skip 和only 字段如何使用?

157 阅读2分钟

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

大家好,我是阿萨。昨天学习了Cypress的钩子函数。今天我们学习skip 和only。 

平时运行自动化测试的过程中,经常2种场景:

  1. 有开发只修改了某个模块的场景。这个时候期望只运行某个模块。

  2. TDD的场景下,某个模块还没有实现代码,但是测试用例已经写了,但是不想运行这个测试用例。

这2种场景就是今天我们要学习的skip 和only 字段。

今天我们就来学习下。
一. skip我们今天先学习下skip,讲解之前,我们还是用昨天的例子,给describe 和it 分别添加skip 字段。
通过添加.skip(),可以告诉Cypress忽略测试用例。跳过的任何内容都将被标记为pending,并记录在报告里。

describe('1st Describe to show 1st suite ', () => {
     describe.skip('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)
     })
     
     it.skip('3rd test', () => { 
     cy.log('3rd test')
     assert.equal(true, true)
     })

})

context.skip('2nd suite', () => {
it('first test', () => { 
cy.log('first test')
assert.equal(true, true)
}) 

it('2nd test', () => {
cy.log('2nd test')
assert.equal(true, true)
}) 

it('3rd test', () => {
cy.log('3rd test')
assert.equal(true, true) 
})
})

测试用例执行结果。

Image

从结果中我们可以看出来,只要describe 添加了skip, 整个测试套件都不会执行。
给it或者specify 添加了skip 表示该测试用例不会执行。

二. only
这就是独占特性。 只运行指定的套件或测试用例,方法是将.only()附加到函数中.我们给describe 和it 添加下only ,看下结果。

describe('1st Describe to show 1st suite ', () => {
    describe.only('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)    
        })    
        
        it.only('3rd test', () => {        
        cy.log('3rd test')        
        assert.equal(true, true)    
        })
        })

        context.only('2nd suite', () => {    
        it('first test', () => {        
        cy.log('first test')        
        assert.equal(true, true)    
        })    
        
        it('2nd test', () => {        
        cy.log('2nd test')        
        assert.equal(true, true)    
        })    
        
        it('3rd test', () => {        
        cy.log('3rd test')        
        assert.equal(true, true)    
        }) 
        })

代码执行结果

Image

从结果来看,只有标记了only的才会执行,其他的都会忽略。
文章开头列举的2个场景。场景1 和场景2 分别需要用那个字段?你学会了吗?