【问题标题】:AfterEach and BeforeEach only for describe()sAfterEach 和 BeforeEach 仅适用于 describe()s
【发布时间】:2019-01-03 04:13:07
【问题描述】:

我有这个演示代码。

describe('demo', () => {
      beforeEach( async () => {
        console.log('->before each')
      })

      afterEach( async () => {
        console.log('->after each')
      })

      describe('->1', () => {
        it('->1.1', async () => {
            console.log('->1.1')
        })

        it('->1.2', async () => {
          console.log('->1.2')
        })
      })

      describe('->2', () => {
        it('->2.1', async () => {
            console.log('->2.1')
        })

        it('->2.2', async () => {
          console.log('->2.2')
        })
      })
})

我正在等待这个结果:

->before each
->1
    ->1.1
    ->1.2
->after each
->before each
->2
    ->2.1
    ->2.2
->after each

我希望 afterEach 和 beforeEach 只在 describe()s 之前和之后运行,而不是 it()s。

实际工作原理:

->1
    ->before each
    ->1.1
    ->after each
    ->before each
    ->1.2
    ->after each

->2
    ->before each
    ->2.1
    ->after each
    ->before each
    ->2.2
    ->after each

我认为 afterEach 和 beforeEach 只能在同一级别上运行,而不是在 cildren 中。

谢谢!

【问题讨论】:

    标签: jasmine protractor


    【解决方案1】:

    是的,不幸的是 beforeEach()afterEach() 运行每个 it() 块。但是您可以使用beforeAll()afterAll() 重构您的测试,如下所示:

    describe('demo', () => {
    
      describe('->1', () => {
        beforeAll(async () => {
          console.log('beforeAll');
        });
    
        afterAll(async () => {
          console.log('afterAll');
        });
    
        it('->1.1', async () => {
          console.log('->1.1');
        });
    
        it('->1.2', async () => {
          console.log('->1.2');
        });
      });
    
      describe('->2', () => {
        beforeAll(async () => {
          console.log('beforeAll');
        });
    
        afterAll(async () => {
          console.log('afterAll');
        });
        it('->2.1', async () => {
          console.log('->2.1');
        });
    
        it('->2.2', async () => {
          console.log('->2.2');
        });
      });
    });
    

    输出

    ->beforeAll
    ->1
        ->1.1
        ->1.2
    ->afterAll
    ->beforeAll
    ->2
        ->2.1
        ->2.2
    ->afterAll
    

    这为您提供了预期的结果,但您必须编写更多代码。但是在测试中,有一些冗余代码是可以的。

    【讨论】:

      【解决方案2】:

      我认为您需要另一个注释

      beforeAll(functionopt, timeoutopt) - execute once before for a describe
      afterAll(functionopt, timeoutopt) - execute once after for a describe
      

      更多详情here

      【讨论】:

        猜你喜欢
        • 2013-12-31
        • 1970-01-01
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 2016-10-21
        • 2013-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多