V
V
Vsevolod Kaloshin2015-07-12 18:02:53
JavaScript
Vsevolod Kaloshin, 2015-07-12 18:02:53

How can you return a value from an asynchronous function in the before block in mocha so that you can use this value in the same describe in the function?

Hello!
Faced a problem when writing tests. I would like to cut down on the amount of repetitive code by putting it in a function that accepts values.
Test pseudocode:

var repeatTests = function(value){

    it ('test1 use value', function(done){
        console.log (value) // return undefined
        ...
    }

    it ('test2 use value', function(done){
       console.log (value) // return undefined
        ...
}

    ...

}

describe ('test', function(){

    var _value
    before(function(done){

        asyncFunction(function(err, value){
            ...    
            _value = value
            ...
            done();
        }

    })

    repeatTests(_value) // value is undefined


})

But this test won't work because _value hasn't changed yet, because it's being changed in the async function.
But this test will work:
describe ('test', function(){

    var _value
    before(function(done){

        asyncFunction(function(err, value){
            ...
            _value = value
            ...

            done();
        }

    })

    it ('test1 use value', function(done){
        console.log(_value); // return _value
        ...
    }

    it ('test2 use value', function(done){
        console.log(_value); // return _value
        ...
    }
        ...
})

If you make a callback wrapper over it, mocha simply does not read them, and if you wrap it over describe, then the outputs of all tests are spoiled, since their results are shown after other tests have been completed, and it is no longer possible to understand which test block these tests belong to.
If you do this for each block, then the size of the code will increase with very much repeating code.
If you make an array of values, and then use array.forEachit, it’s also not an option, since there will be others repeatTestsin the same. It seems like a banal task, but somehow you can’t guess how to do it) describeit

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Serykh, 2015-07-16
@seryh

Alternatively, use async.waterfall()
https://www.npmjs.com/package/async#waterfall

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question