摩卡 - 在每个之前或之前首先运行?

时间:2016-04-20 21:48:38

标签: node.js express mocha

我的网络应用程序的规格如下:

describe('Hook them up', () => {

    var server;

    beforeEach(done => {
        server = app.listen(done);
    });

    before(done => {
       // Does this run before or after "beforeEach"
       // If I try to access the api at this point I get an ECONNREFUSED
    });

    after(done => {
        server.close(done);
    });


    it('should set the \'createdAt\' property for \'DndUsers\' objects', done => {
        api.post('/api/tweets')
            .send({ text: 'Hello World' })
            .then(done)
            .catch(err => {
                console.log(err);
                done();
            });
    });
});

在我的其他一些项目中,如果我尝试访问before块中的api,它可以正常运行,就像beforeEach已经运行一样。

1 个答案:

答案 0 :(得分:4)

See my answer here一个非常相似的问题。

Mocha的测试运动员在Hooks section of the Mocha Test Runner中最好地解释了此功能。

从Hooks部分:

describe('hooks', function() {

    before(function() {
        // runs before all tests in this block
    });

    after(function() {
        // runs after all tests in this block
    });

    beforeEach(function() {
        // runs before each test in this block
    });

    afterEach(function() {
        // runs after each test in this block
    });

    // test cases
    it(...);  // Test 1
    it(...);  // Test 2
});

您可以将这些例程嵌套在其他描述块中,这些块也可以具有before / beforeEach例程。

这应该给你

hooks
    before
        beforeEach
            Test 1
        afterEach
        beforeEach
            Test 2
        afterEach
    after