Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

javascript - mocha pass variable to the next test

describe('some test', function(){
    // Could put here a shared variable
    it('should pass a value', function(done){
        done(null, 1);
    });
    it('and then double it', function(value, done){
        console.log(value * 2);
        done();
    });
});

The above currently would not work in mocha.

A solution would be to have a variable shared between the tests, as shown above.

With async.waterfall() this is very possible and I really like it. Is there any way to make it happen in mocha?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...