我有这个演示代码。

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 仅在同一级别上运行,而不是在 child 中运行。

谢谢!

最佳答案

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

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

关于jasmine - AfterEach 和 BeforeEach 仅用于 describe()s,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51534192/

10-09 16:52