Search code examples
ecmascript-6traceur

How to test an ES6 generator function from an ES5 test framework


Given an ES6 class with generator function how do you run that generator function from ES5 code:

class GeneratorClass {

    constructor() {
        this.ary = [1, 2, 3];
    }

    *[Symbol.iterator]() {
        for (let el of this.ary) {
            yield el;
        }
    }

}

// This runs fine transcompiled (traceur)
var iterableObj = new GeneratorClass();
for (let el of iterableObj) {
    console.log(el);
}

From an ES5 testing framework:

TestCase('GeneratorClassTest', {
    setUp: function () {
        console.log('in setup');
        var iterableObj = new GeneratorClass();
        for (var el in this.iterableObj) {
            console.log(el);
        }
    },

    testConstructor: function() {

    }  
});

This does not throw any errors, will run the setup function, however does not iterate through the array.


Solution

  • If you're just requiring your ES6 module from runtime which only supports ES5, you can't do this.

    But if you're compiling your ES6 module into ES5 using babel or traceur and then requiring your compiled module - you can test your generator in ES5 runtime. Just not use for of loop, create iteratorObj using Symbol.iterator method, and the use when loop and next method of iterator.

    For your example:

    TestCase('GeneratorClassTest', {
        setUp: function () {
            console.log('in setup');
            var generator = new GeneratorClass();
            var next, iterableObj = generator[Symbol.iterator]();
    
            while ((next = iterableObj.next()) && !next.done) {
                console.log(next.value);
            }
        },
    
        testConstructor: function() {
    
        }
    });