javascript - Karma/Istanbul Code Coverage 找不到函数,总是返回 100%

标签 javascript code-coverage karma-runner browserify istanbul

我正在尝试为我的 Karma 测试添加代码覆盖率,但是尽管它找到了我正在测试的正确 JS 文件,但它没有在这些文件中找到函数。

根据我目前所读到的内容,我认为这与文件在传递给 Istanbul 尔进行报道之前没有被正确浏览有关,但诚然,我对此并不陌生,所以我希望得到一些建议。

这是我的 JS 文件(common.js):

var applicationSettings = require('./settings');

var common = {
    getAjaxBaseUrl: function () {
        var strVirtualDirectory = applicationSettings.VirtualDirectory;
        if (strVirtualDirectory.length > 1) {
            if (!strVirtualDirectory.startsWith("/")) {
                strVirtualDirectory = "/" + strVirtualDirectory;
            }
        }
    return strVirtualDirectory;
   }
}
module.exports = common;

下面是我写的测试:

it('Client - Should get correct AjaxBaseUrl with /', function () {
    var clientSettings = require('./../client/scripts/settings');
    var clientCommon = require('./../client/scripts/common');

    clientSettings.VirtualDirectory = '/VD';
    expect(clientCommon.getAjaxBaseUrl()).to.equal('/VD');

});

it('Client - Should get correct AjaxBaseUrl without /', function () {
    var clientSettings = require('./../client/scripts/settings');
    var clientCommon = require('./../client/scripts/common');

    clientSettings.VirtualDirectory = 'VD';
    expect(clientCommon.getAjaxBaseUrl()).to.equal('/VD');
});

我的 Karma.conf 如下:

// Karma configuration
// Generated on Mon Jan 11 2016 09:43:00 GMT+0000 (GMT Standard Time)

module.exports = function (config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['phantomjs-shim', 'browserify', 'mocha'],

        // list of files / patterns to load in the browser
        files: [
            'https://code.jquery.com/jquery-2.2.0.min.js',
            'http://cdn.kendostatic.com/2015.3.1111/js/kendo.all.min.js',
            'test_unit/*Spec.js',
            'client/scripts/*.js'
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'test_unit/*Spec.js': ['browserify'],
            'client/scripts/*.js': ['browserify', 'coverage']    
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'junit'],

        // Configure jUnit reporter
        junitReporter: {
            outputDir: '', // results will be saved as $outputDir/$browserName.xml 
            outputFile: undefined, // if included, results will be saved as $outputDir/$browserName/$outputFile 
            suite: '', // suite will become the package name attribute in xml testsuite element 
            useBrowserName: true // add browser name to report and classes names 
        },

        // Configure coverage reporter
        coverageReporter: {
            type: 'html',
            dir: 'test_coverage',
            subdir: '.',
            file: 'coverage.htm'
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        browserify: {
            configure: function (bundle) {
                bundle.transform('reactify', { extensions: ['.jsx'] });
            }        
        },        

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

    })
}

这确实会生成报告,但显示 100%,并且在 common.js 文件中找到的唯一行是:

require("C:\\Source\\ProjectName\\client\\scripts\\common.js");

我试图将 Browerify-Istanbul 添加到组合中,方法是在 Karma.conf 的顶部添加一个要求,在 browserify 部分添加一个额外的转换

bundle.transform(istanbul)

然而,这只会让我的测试失败并抛出几个错误:

undefined is not an object (evaluating '__cov_qQLFhXEMt7fatxiMx0_vQQ.b[' 1'][0]') getAjaxBaseUrl@C:/Users/CHARLE~1.WIC/AppData/Local/Temp/0d61da722d2838c9 600d83d1cbb4c0b8.browserify:43:1498 C:/Users/CHARLE~1.WIC/AppData/Local/Temp/0d61da722d2838c9600d83d1cbb4c0b 8.browserify:51742:1849

16 02 2016 09:14:08.515:ERROR [coverage]: [TypeError: Cannot read property 'star t' of undefined] TypeError: Cannot read property 'start' of undefined at C:\Source\ProjectName\node_modules\istanbul\lib\o bject-utils.js:59:44 at Array.forEach (native) at Object.addDerivedInfoForFile (C:\Source\ProjectName\node_modules\istanbul\lib\object-utils.js:58:37) at Object.Collector.fileCoverageFor (C:\Source\ProjectName\node_modules\istanbul\lib\collector.js:94:15) at C:\Source\ProjectName\node_modules\istanbul\lib\r eport\html.js:558:90 at Array.forEach (native) at HtmlReport.Report.mix.writeReport (C:\Source\ProjectName\node_modules\istanbul\lib\report\html.js:557:27) at writeReport (C:\Source\ProjectName\node_modules\k arma-coverage\lib\reporter.js:62:16) at C:\Source\ProjectName\node_modules\karma-coverage \lib\reporter.js:288:11 at C:\Source\ProjectName\node_modules\karma\lib\help er.js:82:7 at FSReqWrap.oncomplete (fs.js:82:15)

我是不是遗漏了什么,或者以错误的方式解决了这个问题?

最佳答案

我遇到了完全相同的问题。对我有用的是从预处理器部分删除“覆盖”并使用 browserify-istanbul。此外,您希望配置 browserify-istanbul 以忽略您的测试文件。

所以你的预处理器应该看起来像(删除“覆盖”):

// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
    'test_unit/*Spec.js': ['browserify'],
    'client/scripts/*.js': ['browserify']    
},

你的 browserify 配置应该是这样的:

browserify: {
    configure: function (bundle) {
        bundle.transform('reactify', { extensions: ['.jsx'] });
        bundle.transform(require('browserify-istanbul')({
          ignore: ['**/test_unit/**']
        }));
    }        
},        

希望对你有帮助

关于javascript - Karma/Istanbul Code Coverage 找不到函数,总是返回 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35428753/

相关文章:

javascript - Prototype、Dojo 和 Scriptaculous 结合在一起

javascript - 如何在 WebStorm 中打开 jscoverage 结果

javascript - karma 覆盖率显示 0/0,100% 覆盖率

Angular、Karma 和 Jasmine 报告颜色

Python 全局模拟函数有效,但本地模拟失败

angularjs - AngularJS 单元测试中模拟 $compileProvider 的详细信息

javascript - 检查一个 ajax 调用是否正在进行中,以便我不会触发另一个调用

javascript - 如何使用 JavaScript(外部域)解析 RSS 提要?

javascript - 如何通过浏览器开发工具知道用户已到达页面末尾

scala - 检索踏板内部的凿子源描述