关于javascript:使用嵌套的describe块调用beforeEach和afterEach

Calling beforeEach and afterEach with nested describe blocks

我正在尝试在我正在编写的jasmine测试套件的每个嵌套描述之前和之后调用一些逻辑。

我现在有这样的事情:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
describe('Outer describe', function () {
    beforeEach(function () {
        login();
        someOtherFunc();
    });

    afterEach(function () {
        logout();
    });

    describe('inner describe', function () {
        it('spec A', function () {
                expect(true).toBe(true);
        });

        it('spec B', function () {
                expect(true).toBe(true);
        });
    });
});

我在内部描述中为每个it调用了beforeEachafterEach中的函数。我只希望对外部的每个内部描述调用一次。

这可能吗?


我认为您应该在描述中使用'beforeAll'和'afterAll'作为规范。以下摘自jasmine网站:http://jasmine.github.io/2.1/introduction.html

The beforeAll function is called only once before all the specs in
describe are run, and the afterAll function is called after all specs
finish. These functions can be used to speed up test suites with
expensive setup and teardown.

However, be careful using beforeAll and afterAll! Since they are not
reset between specs, it is easy to accidentally leak state between
your specs so that they erroneously pass or fail.


为此,我定义了一个通用函数,然后在每个嵌套的describebeforeAll / afterAll中引用它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
describe('Wrapper', function() {
  var _startup = function(done) {
    login();
    window.setTimeout(done, 150);
  };

  var _shutdown = function() {
    logout();
  };

  describe('Inner 1', function() {
    beforeAll(_startup);
    afterAll(_shutdown);
  });

  describe('Inner 2', function() {
    beforeAll(_startup);
    afterAll(_shutdown);
  });

  describe('Inner 3', function() {
    beforeAll(_startup);
    afterAll(_shutdown);
  });
});

这似乎是最干净的解决方案。