Testing within a javascript closure

前端 未结 3 1087
臣服心动
臣服心动 2020-12-31 06:26

Is it possible to unit test javascript functions that exist within a closure, so for example, given the following:

(function() {
  var a = function() {
    /         


        
3条回答
  •  时光取名叫无心
    2020-12-31 06:51

    Revisiting the question 4 years on, I now have a better solution.

    Generate a testable version of your code as a build step.

    Say I'm using Gulp to minify my JavaScript, and my code looks like this:

    var a = function() {}
    window.b = function() {}
    

    Not the absence of a closure. Now I set up a gulp task and have it watch my code, like so:

    gulp.task('js', function () {
      return gulp.src([dirs.js.src, '*.js'].join('/'))
        .pipe(wrap('(function() {\n<%= contents %>\n})();'))
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(gulp.dest(dirs.js.dest));
    });
    

    This will wrap my code in the IIFE producing the following output:

    (function() {
    var a = function() {}
    window.b = function() {}
    )();
    

    Generating the testable version

    Now I add another Gulp task, like this

    gulp.task('testJs', function () {
      return gulp.src([dirs.test.src, '*.js'].join('/'))
        .pipe(wrap(
          [
            '(function() {',
              '<%= contents %>',
              '// Smuggle locals out of closure for testing',
              'window.a = a;',
            '})();'
          ].join('\n')
        ))
        .pipe(concat(package.name + '.testable.js'))
        .pipe(gulp.dest(dirs.test.dest));
    });
    

    This will generate the following unsafe but testable code right in my test directory:

    (function() {
    var a = function() {}
    window.b = function() {}
    // Smuggle locals out of closure for testing
    window.a = a;
    )();
    

    Add a watch task...

    gulp.task('watch', function() {
      gulp.watch([dirs.js.src, '**', '*.js'].join('/'), ['js', 'testJs']);
    });
    

    ...and you're done.

    See here

    See here for an example:

    https://github.com/forwardadvance/ng-tweets

提交回复
热议问题