在javascript封闭内测试 [英] Testing within a javascript closure

查看:119
本文介绍了在javascript封闭内测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以对闭包中存在的javascript函数进行单元测试,例如,给定以下内容:

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

(function() {
  var a = function() {
    //do something
  }
  window.b =  function() {
    // do something else
  }
})();

是否可以单元测试函数a而不暴露?

Is it possible to unit test function a without exposing it? If not, is there a good way to expose a, but only in test mode?

推荐答案

回到问题4年后,我现在有一个更好的解决方案。

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

我使用Gulp来缩小我的JavaScript,我的代码看起来像这样:

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

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

不是没有闭包。现在我设置了一个gulp任务,并让它看我的代码,如下:

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));
});

这将包装我的代码在IIFE产生以下输出:

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

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



生成可测试的版本



添加另一个Gulp任务,像这样

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']);
});

...完成操作。

查看范例:

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

这篇关于在javascript封闭内测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆