mocha pass variable to the next test

It is much preferable to keep the tests isolated so that one test does not depend on a computation performed in another. Let's call the test that should pass a value test A and the test that should get it test B. Some question to consider:

  1. Are test A and test B really two different tests? If not, they could be combined.

  2. Is test A meant to provide test B with a fixture to test against? If so, test A should become the callback for a before or beforeEach call. You basically pass the data around by assigning it to variables in the closure of describe.

    describe('some test', function(){
        var fixture;
    
        before(function(done){
            fixture = ...;
            done();
        });
    
        it('do something', function(done){
            fixture.blah(...);
            done();
        });
    });
    

I've read Mocha's code, and provided I'm not forgetting something, there is no way to call describe, it, or the done callback to pass values around. So the method above is it.


Very much agree with what Louis said, and those are the reasons that Mocha doesn't actually support it. Think of the async method you referenced; if your first test fails you get a waterfall failure across the rest of them.

Your only way to go about it is, as you say, to stick a variable at the top:

describe('some test', function(){
    var value = 0;
    it('should pass a value', function(done){
        value = 5;
        done();
    });
    it('and then double it', function(done){
        console.log(value * 2); // 10
        done();
    });
});