javascript - 使用 grunt 和 qunit 进行日志记录

标签 javascript unit-testing gruntjs

我正在使用 grunt/qunit 运行 javascript 单元测试。有时测试失败是因为例如源文件中的语法错误(如果在测试文件中引入语法错误,文件信息可以正常工作)。当发生这种情况时,grunt 只打印行号而不是问题所在的文件。

Running "qunit:all" (qunit) task
Warning: Line 99: Unexpected identifier Use --force to continue.

Aborted due to warnings.

这没什么用,因为我有 100 个 js 文件。我调查过:

https://github.com/gruntjs/grunt-contrib-qunit

并尝试将以下内容添加到我的 Gruntfile.js (grunt.event.on):

module.exports = function(grunt) {
    "use:strict";
    var reportDir = "output/reports/"+(new Date()).getTime().toString();
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        qunit: {
            options: {
                '--web-security': 'no',
                coverage: {
                    src: ['../src/**/*.js'],
                    instrumentedFiles: 'output/instrument/',
                    htmlReport: 'output/coverage',
                    coberturaReport: 'output/',
                    linesTresholdPct: 85
                }
            },
            all: ["testsSuites.html"]
        }
    });


    // Has no effect
    grunt.event.on('qunit.error.onError', function (msg, stack) {
        grunt.util._.each(stack, function (entry) {
            grunt.log.writeln(entry.file + ':' + entry.line);
        });
        grunt.warn(msg);
    });     

    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.loadNpmTasks('grunt-qunit-istanbul');
    grunt.registerTask('test', ['qunit']);

其中 testsSuites.html 包含:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="qunit/qunit.css">
    <script src="qunit/qunit.js"></script>
    <script src="sinonjs/sinon-1.7.3.js"></script>
    <script src="sinonjs/sinon-qunit-1.0.0.js"></script>

    <!-- Sources -->
    <script src="../src/sample.js"></script>

    <!-- Test-->
    <script src="test/sample-test.js"></script>

  </head>
  <body>
    <div id="qunit"></div>
    <div id="qunit-fixture"></div>
    <script>
    </script>
  </body>
</html>

但是问题所在的源文件还是没有打印出来。 Grunts 是否无法验证源代码/显示行号/文件(例如语法错误所在的位置)?

我也试过运行:

grunt test --debug 9

它会打印一些调试信息,但不会打印任何有关 javascript 源代码中语法错误的信息。

我已经尝试安装 JSHint 并在我所有的 javascript 源文件上调用它:

for i in $(find ../src -iname "*.js"); do jshint $i; done

现在我遇到了很多错误,但 Grunt 仍然很高兴。如果我引入一个简单的语法错误,例如:

(function(){
   var sampleVar 32;

}

在 Grunt 中引发错误:

Running "qunit:all" (qunit) task
Warning: Line 2: Unexpected number Use --force to continue.

Aborted due to warnings.

它只是消失在 JSHint 生成的错误流中。如何从实际上会使 Grunt 失败的严重错误中过滤 JSHint“警告”?

或者应该配置 qunit 以获得更详细的输出?

最佳答案

grunt-contrib-qunit 将在遇到语法错误时显示文件名。采用这个简化版本的 Gruntfile.js:

module.exports = function(grunt) {
    "use:strict";
    grunt.initConfig({
        qunit: {
            options: { '--web-security': 'no' },
            all: ["testsSuites.html"]
        }
    });

    grunt.loadNpmTasks('grunt-contrib-qunit');
};

运行它会给出您正在寻找的错误:

$ grunt qunit
Running "qunit:all" (qunit) task
Testing testsSuites.html F.
>> global failure
>> Message: SyntaxError: Parse error
>> file:///tmp/src/sample.js:2

Warning: 1/2 assertions failed (17ms) Use --force to continue.

Aborted due to warnings.

您遇到的问题看起来是 grunt-qunit-istanbul 中的错误(?)。您收到的警告:

Warning: Line 99: Unexpected identifier Use --force to continue.

Grunt 正在处理未捕获的异常。 grunt-qunit-istanbul 任务引发异常。您可以通过修改原始 Gruntfile.js 中的这一行来证明这一点:

src: ['../src/**/*.js'],

到:

src: ['../src/**/*.js.nomatch'],

这将阻止 grunt-qunit-istanbul 在 Qunit 运行之前查找和解析任何 Javascript 文件。如果你让 Qunit 运行,它的错误处理程序会打印出你想要的带有语法错误的文件名。

唯一的解决方法是我所描述的解决方法,或者修补 grunt-qunit-istanbul 以像 Qunit 那样为解析错误添加错误处理程序。

修补 grunt-qunit-istanbul

抛出异常的函数是Instrumenter.instrumentSync ,它应该这样做:

instrumentSync ( code, filename )

Defined in lib/instrumenter.js:380

synchronous instrumentation method. Throws when illegal code is passed to it

您可以通过包装函数调用来修复它:

diff -r 14008db115ff node_modules/grunt-qunit-istanbul/tasks/qunit.js
--- a/node_modules/grunt-qunit-istanbul/tasks/qunit.js  Tue Feb 25 12:14:48 2014 -0500
+++ b/node_modules/grunt-qunit-istanbul/tasks/qunit.js  Tue Feb 25 12:19:58 2014 -0500
@@ -209,7 +209,11 @@

       // instrument the files that should be processed by istanbul
       if (options.coverage && options.coverage.instrumentedFiles) {
-        instrumentedFiles[fileStorage] = instrumenter.instrumentSync(String(fs.readFileSync(filepath)), filepath);
+        try {
+          instrumentedFiles[fileStorage] = instrumenter.instrumentSync(String(fs.readFileSync(filepath)), filepath);
+        } catch (e) {
+          grunt.log.error(filepath + ': ' + e);
+        }
       }

       cb();

然后测试将继续运行(并通知您语法错误):

$ grunt qunit
Running "qunit:all" (qunit) task
>> /tmp/src/sample.js: Error: Line 2: Unexpected number
Testing testsSuites.html F.
>> global failure
>> Message: SyntaxError: Parse error
>> file:///tmp/src/sample.js:2

Warning: 1/2 assertions failed (19ms) Use --force to continue.

Aborted due to warnings.

关于javascript - 使用 grunt 和 qunit 进行日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21811719/

相关文章:

javascript - 隐藏 div(仅包含 script 标签)

Javascript(使用 Phaser)错误显示游戏颜色 - 括号

python - 对于假设策略,如何从 max_value 而不是 min_value 开始测试用例?

angularjs - 如何在 AngularJS 中模拟包含资源的服务

javascript - 使用自定义任务扩展 meteor 的构建

javascript - 带 Web API 安全问题的 Spa 应用程序。使用 JWT 登录的用户可以向 API 发出随机请求吗

iphone - Objective-C 单元测试是否需要头文件?

javascript - 带有自定义 json 配置的 grunt 任务

javascript - GruntJs 任务问题

javascript - Bootstrap 3,导航栏中的下拉菜单不针对单击 Internet Explorer 时的 href