AfterEach和BeforeEach仅用于describe()

时间:2018-07-26 08:20:48

标签: jasmine protractor

我有这个演示代码。

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中运行。

谢谢!

2 个答案:

答案 0 :(得分:2)

不幸的是,每个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

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

答案 1 :(得分:1)

我认为您需要另一个注释

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

更多详细信息here