How does variable scope work within the Mocha test framework?

给你一囗甜甜゛ 提交于 2019-11-30 11:24:38

Variable scoping in Mocha is exactly the same as in any other JavaScript code. Your problem is that you do not realize in which order Mocha will execute your code. This is what happens:

  1. You create your unit instance and call disable on it.

  2. You register your first test. That's what it does: it registers a test for future execution. The test does not execute now.

  3. You call unit.nextTurnReset(); which resets your object's state.

  4. You register your second test. Again it does not execute now.

  5. You reset your object again.

  6. You register your last test.

After this, Mocha takes the tests you registered and runs them. By the time your tests are running your object is in its reset state, not disabled.

It seems to me that given the desired behavior you describe, your code should be:

describe('#disable()', function() {
    var unit = tests.newUnit();

    beforeEach(function () {
        unit.nextTurnReset();
    });

    it('disabled off turn?', function() {
        unit.disable();
        (unit.isDisabled()).should.be.exactly(true);
    });

    it('disabled on next turn?', function() {
        (unit.isDisabled()).should.be.exactly(false);
    });
});

The code passed to beforeEach is run before each test you've registered so it resets the object at the right time.

Passing state between examples is not a very good practice. What happens if you need to run tests in the random order? Or somebody in the project decides to move examples around?

For me having the following two examples seems to be enough to test Unit#disable properly

describe('#disable()', function() {
    it('gets disabled when called on an enabled', function() {
        var unit = tests.newUnit();
        unit.disable();

        (unit.isDisabled()).should.be.exactly(true);
    });

    it('gets enabled when called on a disabled', function() {
        var unit = tests.newUnit();
        unit.disable();
        unit.disable();

        (unit.isDisabled()).should.be.exactly(false);
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!