【问题标题】:Cypress hooks in grouped describe分组描述中的柏树钩子
【发布时间】:2021-05-06 05:52:56
【问题描述】:

我想为每个描述调用执行一个钩子。我的结构应该是这样的:

describe('Main', ()=> {
  beforeEach(() => {
    // should call for every describe
  })
  
  describe('Sub', () => {
    it('some tests', ()=> {
      
    })
    
    it('some tests2', ()=> {
      
    })
  })
  
  describe('Sub 2', () => {
    it('some tests', ()=> {
      
    })
  })
})

我尝试执行此操作,但 beforeEach 每次测试都会触发,而不是每次描述。

【问题讨论】:

    标签: javascript reactjs cypress


    【解决方案1】:

    由于beforeEach() 不会在每个描述块之前执行,因此您必须创建一个自定义函数来实现这一点。你可以做这样的事情。创建一个自定义函数,而不是 describe 块,您可以调用此函数来每次运行 before 块。

    function customSuite(name, tests) {
      describe(name, function() {
        before(function() {
          //Do Something
        });
        tests();
      });
    }
    
    describe('Main', () => {
    
      customSuite('Sub1', function() {
        it('some tests', function() {
    
        })
    
        it('some tests2', function() {
    
        })
      })
    
      customSuite('Sub2', function() {
        it('some tests', function() {
    
        })
      })
      
    })
    

    【讨论】:

      【解决方案2】:

      您可以修补标准的describe() 函数,它将透明地添加钩子。

      const originalDescribe = global.describe
      const describe = (title, callback) => {
        originalDescribe(title, () => {
          before(() => {
            console.log('describe', title)
          });
          callback();
        });
      }
      
      describe('Main', ()=> {
        
        describe('Sub', () => {
          it('some tests', ()=> {
            console.log('it', 1)
          })
          
          it('some tests2', ()=> {
            console.log('it', 2)
          })
        })
        
        describe('Sub 2', () => {
          it('some tests', ()=> {
            console.log('it', 3)
          })
        })
      })
      

      或者另一种(更简单的)方法就是在每个 describe() 块的开头调用你 beforeDescribe() 钩子。

      const beforeDescribeHook = () => {
        const title = Cypress.mocha.getRunner().suite.title;
        console.log('describe', title)
      }
      
      describe('Main', ()=> {
      
        before(beforeDescribeHook)
        
        describe('Sub', () => {
      
          before(beforeDescribeHook)
      
          it('some tests', ()=> {
            console.log('it', 1)
          })
          
          it('some tests2', ()=> {
            console.log('it', 2)
          })
        })
        
        describe('Sub 2', () => {
      
          before(beforeDescribeHook)
      
          it('some tests', ()=> {
            console.log('it', 3)
          })
        })
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-27
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        • 2015-05-01
        • 1970-01-01
        相关资源
        最近更新 更多