Coder Social home page Coder Social logo

istanbul-instrumenter-loader's Introduction

npm node deps tests coverage chat

Istanbul Instrumenter Loader

Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting

Install

npm i -D istanbul-instrumenter-loader

References

Structure

├─ src
│ |– components
│ | |– bar
│ | │ |─ index.js
│ | |– foo/
│     |– index.js
|– test
| |– src
| | |– components
| | | |– foo
| | | | |– index.js

To create a code coverage report for all components (even for those for which you have no tests yet) you have to require all the 1) sources and 2) tests. Something like it's described in "alternative usage" of karma-webpack

test/index.js

// requires all tests in `project/test/src/components/**/index.js`
const tests = require.context('./src/components/', true, /index\.js$/);

tests.keys().forEach(tests);

// requires all components in `project/src/components/**/index.js`
const components = require.context('../src/components/', true, /index\.js$/);

components.keys().forEach(components);

ℹ️ This file will be the only entry point for karma

karma.conf.js

config.set({
  ...
  files: [
    'test/index.js'
  ],
  preprocessors: {
    'test/index.js': 'webpack'
  },
  webpack: {
    ...
    module: {
      rules: [
        // instrument only testing sources with Istanbul
        {
          test: /\.js$/,
          use: { loader: 'istanbul-instrumenter-loader' },
          include: path.resolve('src/components/')
        }
      ]
    }
    ...
  },
  reporters: [ 'progress', 'coverage-istanbul' ],
  coverageIstanbulReporter: {
    reports: [ 'text-summary' ],
    fixWebpackSourcePaths: true
  }
  ...
});

with Babel

You must run the instrumentation as a post step

webpack.config.js

{
  test: /\.js$|\.jsx$/,
  use: {
    loader: 'istanbul-instrumenter-loader',
    options: { esModules: true }
  },
  enforce: 'post',
  exclude: /node_modules|\.spec\.js$/,
}

The loader supports all options supported by istanbul-lib-instrument

Name Type Default Description
debug {Boolean} false Turn on debugging mode
compact {Boolean} true Generate compact code
autoWrap {Boolean} false Set to true to allow return statements outside of functions
esModules {Boolean} false Set to true to instrument ES2015 Modules
coverageVariable {String} __coverage__ Name of global coverage variable
preserveComments {Boolean} false Preserve comments in output
produceSourceMap {Boolean} false Set to true to produce a source map for the instrumented code
sourceMapUrlCallback {Function} null A callback function that is called when a source map URL is found in the original code. This function is called with the source filename and the source map URL

webpack.config.js

{
  test: /\.js$/,
  use: {
    loader: 'istanbul-instrumenter-loader',
    options: {...options}
  }
}

Maintainers


Kir Belevich

Juho Vepsäläinen

Joshua Wiens

Michael Ciniawsky

Matt Lewis

istanbul-instrumenter-loader's People

Contributors

buonomo avatar escapedcat avatar filipesilva avatar jakxz avatar joshwiens avatar mattlewis92 avatar michael-ciniawsky avatar simenb avatar sshev avatar sukrosono avatar tarjei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

istanbul-instrumenter-loader's Issues

Upgrading from babel-istanbul-loader, build fails with JSX

I saw that babel-istanbul-loader was deprecated and was pointed to this library as the upgrade. My webpack now fails to build if there is JSX syntax in code.

Does istanbul-instrumenter-loader support react JSX? Do I need any other changes?

Previous config from babel-istanbul-loader:

module: {
      rules: [
        {
          include: [
            path.resolve(__dirname, './src'),
          ],
          test: /\.(js|jsx)$/,
          use: [
            {
              loader: 'babel-loader',
              options: {
                cacheDirectory: true,
              },
            },
          ],
        },
        {
          enforce: 'pre',
          exclude: /\.test\.js|jsx$/,
          include: [
            path.resolve(__dirname, './src'),
          ],
          test: /\.(js|jsx)$/,
          use: [
            {
              loader: 'babel-istanbul-loader',
              options: {
                cacheDirectory: true,
              },
            },
          ],
        },

new config with istanbul-instrumenter-loader:

module: {
      rules: [
        {
          include: [
            path.resolve(__dirname, './src'),
          ],
          test: /\.(js|jsx)$/,
          use: [
            {
              loader: 'babel-loader',
              options: {
                cacheDirectory: true,
              },
            },
          ],
        },
        {
          exclude: /\.test\.js|jsx$/,
          include: [
            path.resolve(__dirname, './src'),
          ],
          test: /\.(js|jsx)$/,
          use: [
            {
              loader: 'istanbul-instrumenter-loader',
              options: {
                esModules: true,
              },
            },
          ],
        },

.babelrc

{
  "plugins": ["dynamic-import-webpack"],
  "presets": [
    "latest",
    "react",
    "stage-3"
  ],
  "env": {
    "test": {
      "plugins": ["istanbul"]
    }
  }
}

Weird Istanbul TypeError "TypeError: Cannot read property 'start' of undefined"

Any idea if this is related to the loader? Perhaps a really slow test?

15 12 2015 16:47:52.674:ERROR [coverage]: [TypeError: Cannot read property 'start' of undefined]
TypeError: Cannot read property 'start' of undefined
at /home/adjavaherian/Desktop/web-off-master/node_modules/istanbul/lib/object-utils.js:59:44
at Array.forEach (native)
at Object.addDerivedInfoForFile (/home/adjavaherian/Desktop/web-off-master/node_modules/istanbul/lib/object-utils.js:58:37)
at Object.Collector.fileCoverageFor (/home/adjavaherian/Desktop/web-off-master/node_modules/istanbul/lib/collector.js:94:15)
at /home/adjavaherian/Desktop/web-off-master/node_modules/istanbul/lib/report/text.js:210:27
at Array.forEach (native)
at TextReport.Report.mix.writeReport (/home/adjavaherian/Desktop/web-off-master/node_modules/istanbul/lib/report/text.js:208:27)
at writeReport (/home/adjavaherian/Desktop/web-off-master/node_modules/karma-coverage/lib/reporter.js:62:16)
at /home/adjavaherian/Desktop/web-off-master/node_modules/karma-coverage/lib/reporter.js:282:11
at Array.forEach (native)
at forEach (/home/adjavaherian/Desktop/web-off-master/node_modules/karma/lib/browser_collection.js:93:21)
at /home/adjavaherian/Desktop/web-off-master/node_modules/karma-coverage/lib/reporter.js:241:16
at Array.forEach (native)
at onRunComplete (/home/adjavaherian/Desktop/web-off-master/node_modules/karma-coverage/lib/reporter.js:240:15)
at null.<anonymous> (/home/adjavaherian/Desktop/web-off-master/node_modules/karma/lib/events.js:13:22)
at emitTwo (events.js:92:20)

Add option for including all sources

First off, I have little understanding of the interactions amongst karma, webpack, istanbul-instrumenter-loader, and karma-coverage. This may not be the appropriate project for my request and, if not, maybe you can point me in the right direction.

The end result I'm looking for is to be able to include sources files that are not required by tests into coverage report without making the suggested index.js file, specifically this part: componentsContext.keys().forEach(componentsContext);.

Why don't I want index.js to execute the modules? Well, it's a long story and a complicated one at that so I'll avoid telling it if possible. What it comes down to though is that the modules throw exceptions unless the tests inject certain things into them (currently we're using inject-loader for this). Because they throw exceptions in this case, no coverage report is rendered. If I don't use the example index.js, source files that are not required by tests are not included in the coverage report.

I see inklings of things that may make this possible. For example, I'm aware of the --include-all-sources command-line flag for istanbul but I'm not using the command-line. I'm aware of work on karma-coverage to allow for this as well as this interim workaround. My attempts at making them work in unison with webpack+istanbul-instrumenter-loader have failed. They make the coverage report, but the source files that are not required by tests still don't show up.

Any insight here? Thank you!

istanbul-instrumenter with karma, TypeScript and webpack

Hi,
I'm using TypeScript via webpack, with one entry point for the source and one entry point for the tests.

Here is my webpack.conf.js file:

module.exports = {
debug: true,
devtool: 'inline-source-map',
output: {
filename: 'all.min.js',
},
module : {
loaders : [
{
test: /.tsx?$/,
include: path.resolve(__dirname, 'src/'),
loader: 'ts-loader'
}
],
postLoaders: [
// instrument only testing sources with Istanbul
{
test: /.tsx?$/,
include: path.resolve(__dirname, 'src/'),
loader: 'istanbul-instrumenter'
}
]
}
}

When adding istanbul-instrumenter as postLoaders it's really working well and I can see all the files separated like I want, but unfortunate I receive this error:

TypeError: Cannot read property 'split' of undefined]
TypeError: Cannot read property 'split' of undefined
at HtmlReport.Report.mix.writeDetailPage

When removing it, all works, but one big bundled file will be exported to the html report.

Can you help me with that?

Thanks,
Best Regards

strange bug I just can pin a description to

When trying to upgrade angular2-webpack-starter (PR PatrickJS/PatrickJS-starter#1297) to [email protected] there's a strange bug...

It happens when using a specific angular configuration to set an import in an NgModule.

When doing so the test breaks, removing istanbul-instrumenter-loader (or reverting back to 0.2.0) removes the issue.

To me it smells like the metadata, the loader might remove some of the metadata of a type when it's not directly used.. I don't know :)

To reproduce clone the repo then update to 1.2.0 and add the code in PatrickJS/PatrickJS-starter#1309

You can look at the issue for some more information.

I'm sorry for lack of information, this is an area i'm not the best in...

JavaScript Foundation License

The license file needs to be updated as part of the transfer into webpack-contrib.

The current copyright holder ( @deepsweet ) needs to to commit the copyright change to act as "signing over" the project to webpack-contrib which is part of the JS Foundation.

The LICENSE needs to be named LICENSE ( no extension ) if it isn't already.

The LICENSE needs to have the following copy.

DO NOT change the license prop in the package.json

Copyright JS Foundation and other contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Error: Unable to lookup source

I'm trying to get coverage tests for my vuejs project. My webpack2 rules look like this...

      rules: [{
        test: /\.js$/,
        exclude: /node_modules|vue\/src|vue-router\//,
        loader: 'babel-loader',
        options: {
          presets: [
            ['es2015', { 'modules': false }]
          ],
          plugins: ['transform-runtime']
        }
      }, {
        test: /\.styl$/,
        loaders: ['style-loader', 'css-loader', 'stylus-loader']
      }, {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          postLoaders: {
            js: 'istanbul-instrumenter-loader?esModules=true'
          }
        }
      }, {
        include: /\.json$/,
        loaders: ['json-loader']
      }, {
        enforce: 'post',
        test: /\.js$/,
        exclude: /node_modules|vue\/src|vue-router\/|test\//,
        loader: 'istanbul-instrumenter-loader',
        query: {
          debug: true,
          preserveComments: true,
          esModules: true
        }
      }]
    },

My karma config looks like this.

        {
          frameworks: ['jasmine'],
          singleRun: true,
          colors: true,
          browsers: ['Chrome'],
          phantomjsLauncher: {
            exitOnResourceError: true
          },
          reporters: ['spec', 'coverage-istanbul'],
          files: [
            { pattern: 'test/unit/**/*-spec.js', watched: false }
          ],
          preprocessors: {
            'test/unit/**/*-spec.js': ['webpack']
          },
          webpack: {
            devtool: 'source-map',
            output: {
            },
            module: webpack.module,
            resolve: webpack.resolve
          },
          webpackMiddleware: {
            noInfo: true,
            stats: 'errors-only'
          },
          coverageIstanbulReporter: {
            dir: './build/reports/unit',
            reports: [ 'text-summary', 'html' ],
            fixWebpackSourcePaths: true,
            'report-options': {
              html: {
                verbose: true,
                subdir: 'html'
              }
            }
          }
        },
        specReporter: {
          suppressSkipped: false
        }
      }

The istanbul-instrumenter-loader is used specifically for the javascript section of the .vue files as a postLoader. When I run karma I'm getting a report but its just an error Error: Unable to lookup source: /Users/user/Development/app/src/components/background.vue?094fc1b7(ENOENT: no such file or directory, open '/Users/user/Development/app/src/components/background.vue?094fc1b7'), note the has on the end of the filename. Is there something I'm doing wrong?

Awesome job on this

Glad to see it!

My next challenge is getting Traceur into the tool chain!

loaderUtils.parseQuery() is deprecated

We started using this loader a few days back and now receive a deprecation warning every time we run our tests. Here is the full waring plus the matching stacktrace:

(node:1873) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
    at Object.parseQuery (/Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/loader-utils/index.js:78:3)
    at Object.module.exports (/Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/istanbul-instrumenter-loader/index.js:15:35)
    at LOADER_EXECUTION (/Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/loader-runner/lib/LoaderRunner.js:119:14)
    at runSyncOrAsync (/Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/loader-runner/lib/LoaderRunner.js:120:4)
    at iterateNormalLoaders (/Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/loader-runner/lib/LoaderRunner.js:229:2)
    at iterateNormalLoaders (/Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/loader-runner/lib/LoaderRunner.js:218:10)
    at /Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/loader-runner/lib/LoaderRunner.js:233:3
    at context.callback (/Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
    at /Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/babel-loader/lib/index.js:159:14
    at /Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/babel-loader/lib/fs-cache.js:113:24
    at /Users/sweingaertner/Sites/standard/standard/vendor/ofcs/ofcs/node_modules/babel-loader/lib/fs-cache.js:44:14
    at Gunzip.onEnd (zlib.js:213:5)
    at emitNone (events.js:91:20)
    at Gunzip.emit (events.js:188:7)
    at endReadableNT (_stream_readable.js:975:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)

No source map support

When using this as a post loader in my webpack config:

webpackConfig.module.postLoaders = [
  {
    test: /\.jsx$/,
    exclude: /(test|node_modules|bower_components)\//,
    loader: 'istanbul-instrumenter'
  }
];

It ends up destroying source maps: devtool: 'source-map',

For now my work around is to do

let istanbulInstrumenter =  {
    test: /\.jsx$/,
    exclude: /(test|node_modules|bower_components)\//,
    loader: 'istanbul-instrumenter'
  };
webpackConfig.module.postLoaders = IS_CI_ENV ? [istanbulInstrumenter] : []

Which works for when I want it to do coverage from my CI environment, but makes it so it's slightly more difficult to get coverage locally.

Improve readme file context being use

I am new to webpack and istanbul, and about to add coverage to my lib.
I just follow the tutorial and found this module here.

I am little bit confuse, do i have to run coverage under webpack or karma?

The readme file is quite nice, but i under options and above maintainer there are sample of file. But no note which file is that?
Also on h3 with Babel no note which file is that.

I want submit a PR when that question is answered. Since two file (test/index.js, karma.conf.js) have note on which file should be edit.

Make babel as peerDependencies

Please, can you remove babel from dependencies ?

It cause errors when babel was at a lower version if we update istanbul-intrumenter-loader to V3.

It's not absolutly required to have babel 7 to get this work and it is not the responsibility of instanbul to provide the babel version to the projet I think.

Doesn't produce coverage

I only get coverage report on files that are imported in test files.
How does it know where are all my source files that need to be checked since it's not set up in config?

Wrong coverage output

I see some weird coverage report output.

this is my karma.conf:

config.set({
        frameworks: [
            'mocha',
            'chai',
            'sinon'
        ],

        client: {
            mocha: {
                reporter: 'html',
                ui: 'bdd'
            }
        },

        files: [
            './WebContent/webappsTest/tests.webpack.js'
        ],

        autoWatch: true,

        browsers: [
            'PhantomJS'
        ],

        preprocessors: {
            './WebContent/webappsTest/tests.webpack.js': ['webpack', 'sourcemap']
        },

        reporters: [
            'progress',
            'mocha',
            'coverage-istanbul'
        ],

        coverageIstanbulReporter: {
            reports: [ 'html', 'text-summary' ],
            fixWebpackSourcePaths: true
        },

        webpack: {
            devtool: 'inline-source-map',
            stats: false,
            module: {
                rules: [
                    {
                        test: /\.js$/,
                        include: path.resolve('WebContent/webapps/'),
                        exclude: '/node_modules/',
                        loader: 'istanbul-instrumenter-loader',
                        options: { esModules : true }
                    },
                    {
                        test: /\.js$/,
                        exclude: '/node_modules/',
                        loader: 'babel-loader',
                        options: {
                            presets: [
                                ['es2015', {modules: false}]
                            ]
                        }
                    }
                ]
            }
        },

        plugins: [
            'karma-webpack',
            'karma-mocha',
            'karma-mocha-reporter',
            'karma-chai',
            'karma-sinon',
            'karma-phantomjs-launcher',
            'karma-chrome-launcher',
            'karma-coverage-istanbul-reporter',
            'karma-sourcemap-loader'
        ]

    });

Now everything works and runs fine, my tests are being executed and my report is being generated but even without zero test cases written my code coverage comes back with certain amount of coverage, which i expected should be 0% since i'm not running a single test case on it.

image

My test file looks like this:

const testsContext = require.context('./', true, /\.test\.js$/);
testsContext.keys().forEach(testsContext);

const componentsContext = require.context('../webapps/', true, /\.js$/);
componentsContext.keys().forEach(componentsContext);

Anything obvious that i'm doing wrong here?

Also what i'm seeing is that my test files are being loaded into the coverage report, if i'm not mistaken they shouldn't be there is that correct?

Thanks

Not getting coverage output

Hello!

I looked for an answer for this and tried multiple things... but I can't get code coverage working, maybe someone can shed a light into what this isn't working:

This is the karma conf file:

/* eslint-disable no-var */
var path = require('path');

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'sinon'],
    files: [
      './test/**/*.js'
    ],
    preprocessors: {
      './test/**/*.js': ['webpack']
    },
    webpack: {
      module: {
        loaders: [
          {
            test: /\.js?$/,
            loaders: ['babel-loader'],
            exclude: /node_modules/
          }
        ],
        postLoaders: [
          {
            test: /\.js$/,
            loaders: ['istanbul-instrumenter'],
            exclude: /(test|node_modules)\//
          }
        ]
      },
      resolve: {
        root: [
          path.join(__dirname, 'src'),
          'node_modules'
        ]
      }
    },
    webpackMiddleware: {
      noInfo: true
    },
    plugins: [
      require('karma-webpack'),
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-phantomjs-launcher'),
      require('karma-coverage'),
      require('karma-sinon'),
      'karma-nyan-reporter',
      'istanbul-instrumenter-loader'
    ],
    reporters: ['nyan', 'coverage'],
    nyanReporter: {
      suppressErrorReport: false
    },
    coverageReporter: {
      type: 'html',
      dir: 'coverage/'
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false
  });
};

When I run karma I don't errors and the tests are being run, but I don't get a folder 'coverage' nor html files created... did I missed something obvious? (this is the first time I'm trying Istanbul code coverage btw)

Thanks!

Error: Unable to lookup source.

Using 3.0.0

Unable to lookup source: /Users/user/ryanown/khlt/registration/src/components/src/components/Reg1.vue

the "src/components" showed twice.

html reports fail w/ v1

When using the following config:

let webpackConfig = require('./webpack.config.js')

const instanbulInstrumenterCfg = {
  test: /\.js$/,
  exclude: /(tests|node_modules|bower_components)\//,
  loader: 'istanbul-instrumenter',
  query: {
    esModules: true
  }
}

webpackConfig.module.postLoaders = [ instanbulInstrumenterCfg ]

module.exports = function (config) {
  config.set({
    autoWatch: false,
    basePath: '',
    browsers: ['Chrome'],
    colors: true,
    concurrency: Infinity,
    coverageReporter: {
      reporters: [
        { type: 'text', subDir: 'text' },
        { type: 'html', subDir: 'html' }
      ],
      dir: 'coverage/'
    },
    frameworks: ['mocha'],
    files: ['tests/index.js'],
    logLevel: config.LOG_INFO,
    plugins: ['karma-chai', 'karma-chrome-launcher', 'karma-mocha',
      'karma-sourcemap-loader', 'karma-webpack',
      'karma-coverage', 'karma-mocha-reporter'],
    port: 9876,
    preprocessors: {
      'tests/index.js': ['webpack', 'sourcemap'],
      'tests/**/*\.test.js': [ 'webpack' ],
      'src/**/*.js': ['coverage', 'webpack']
    },
    reporters: ['progress', 'mocha', 'coverage'],
    singleRun: true,
    webpack: webpackConfig
  })
}

The coverage results do get printed to the terminal, however immediately after that I get this error:

[coverage]: TypeError: Cannot read property 'text' of undefined
    at /Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:288:53
    at Array.forEach (native)
    at annotateBranches (/Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:255:30)
    at HtmlReport.writeDetailPage (/Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:426:9)
    at /Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:489:26
    at SyncFileWriter.writeFile (/Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/util/file-writer.js:57:9)
    at FileWriter.writeFile (/Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/util/file-writer.js:147:23)
    at /Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:488:24
    at Array.forEach (native)
    at HtmlReport.writeFiles (/Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:482:23)
    at /Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:484:22
    at Array.forEach (native)
    at HtmlReport.writeFiles (/Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:482:23)
    at HtmlReport.writeReport (/Users/evansiroky/git/reporter-demo/node_modules/istanbul/lib/report/html.js:566:14)
    at writeReport (/Users/evansiroky/git/reporter-demo/node_modules/karma-coverage/lib/reporter.js:68:16)
    at /Users/evansiroky/git/reporter-demo/node_modules/karma-coverage/lib/reporter.js:296:11
    at /Users/evansiroky/git/reporter-demo/node_modules/karma/lib/helper.js:144:7
    at FSReqWrap.oncomplete (fs.js:123:15)

Getting issue while running the webpack in Jenkins

The webpack tests are running with the coverage summary in my mac when i run nom test and the same way its not coming up with the jenkins console output while i run on jenkins server. Am i missing anything ? teh below is the one it shows in my mac
screen shot 2016-05-10 at 12 52 56 am

in jenkins

screen shot 2016-05-10 at 12 54 22 am

I have made my npm test command returning true always . I have tried both the ways , it never worked for me.

here is my karma conf

// Reference: http://karma-runner.github.io/0.12/config/configuration-file.html
module.exports = function karmaConfig (config) {
config.set({
frameworks: [
// Reference: https://github.com/karma-runner/karma-jasmine
// Set framework to jasmine
'jasmine'
],

reporters: [
  // Reference: https://github.com/mlex/karma-spec-reporter
  // Set reporter to print detailed results to console
  'progress',
    'verbose',
    'dots',

  // Reference: https://github.com/karma-runner/karma-coverage
  // Output code coverage files
  'coverage'
],

files: [
  // Grab all files in the app folder that contain .spec.
  //'src/tests.webpack.js'
  'test/tests.webpack.js'
],

preprocessors: {
  // Reference: http://webpack.github.io/docs/testing.html
  // Reference: https://github.com/webpack/karma-webpack
  // Convert files with webpack and load sourcemaps
  'test/tests.webpack.js': ['webpack', 'sourcemap']
},

browsers: [
  // Run tests using PhantomJS
  'PhantomJS'
],

singleRun: true,

// Configure code coverage reporter
coverageReporter: {
  dir: 'coverage/',
  reporters: [
    {type: 'text-summary'},
    {type: 'html'}
  ]
},

webpack: require('./webpack.config'),

// Hide webpack build information from output
webpackMiddleware: {
  noInfo: 'errors-only'
}

});
};

Document ES2015 Modules Support

I found this comment that explains how to use ES2015 modules with the istanbul-instrumenter-loader. In Webpack 2, it would look like:

use: 'istanbul-instrumenter-loader',
options: {
  esModules: true
}

I tried it and it works. Can that be documented somewhere? I had to hunt through open issues in order to find it.

Deprecated use of non-string passed to loaderUtils.parseQuery()

(node:35555) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
    at Object.parseQuery (/path/to/node_modules/loader-utils/index.js:78:3)
    at Object.module.exports (/path/to/node_modules/istanbul-instrumenter-loader/index.js:15:35)
    at LOADER_EXECUTION (/path/to/node_modules/loader-runner/lib/LoaderRunner.js:119:14)
    at runSyncOrAsync (/path/to/node_modules/loader-runner/lib/LoaderRunner.js:120:4)
    at iterateNormalLoaders (/path/to/node_modules/loader-runner/lib/LoaderRunner.js:229:2)
    at Array.<anonymous> (/path/to/node_modules/loader-runner/lib/LoaderRunner.js:202:4)
    at Storage.finished (/path/to/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:40:15)
    at /path/to/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:77:9
    at /path/to/node_modules/graceful-fs/graceful-fs.js:78:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:415:3)
> npm list istanbul-instrumenter-loader 
...
└── [email protected] 
> npm --version
3.10.9
> node --version
v7.2.0

Getting weird error (false positive)

ERROR in Entry module not found: Error: Cannot resolve module 'istanbul-instrumenter' in /Users/simen/Development/experiments/src/assets/

The weird thing is it obviously works, as I do get coverage report out of it.

coverage as reporter, and added the postLoaders from the readme.

It doesn't fail, so there's no real issue, but it's annoying getting the warning

SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (1:0)

Hi

I want to coverage all files and not only the tests. So I excluded the node_moduels folder. But i get this error on all the others files.

WARNING in ./lib/components/home/home.config.js
Module build failed: SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (1:0)
at Parser.pp.raise (C:\Users\kevin\Documents\Projets\web-template-webpack\node_modules\babylon\lib\parser\location.js:22:13)

This is my karma.config.js:

var webpack = require("webpack");
var path = require("path");
module.exports = function(config) {
    config.set({
        files: [
            './tests.webpack.js'
        ],

        preprocessors: { './tests.webpack.js': ['webpack'] },

        // frameworks to use
        frameworks: ['chai', 'mocha'],

        reporters: ['spec', 'coverage'],

        coverageReporter: {
            type: 'html',
            dir: 'coverage/'
        },

        webpack: {
            // webpack configuration
            module: {
                loaders: [
                    {
                        test: /\.js$/,
                        exclude: [
                            path.resolve('lib/'),
                            path.resolve('node_modules/')
                        ],
                        loaders: ['babel']
                    }
                ],

                postLoaders: [{
                    test: /\.js/,
                    include: path.resolve('lib/'),
                    exclude: /(node_modules)/,
                    loader: 'istanbul-instrumenter'
                }]
            },
            resolve: {
                modulesDirectories: [
                    "",
                    "lib",
                    "node_modules"
                ]
            }
        },

        webpackMiddleware: {
            // webpack-dev-middleware configuration
            noInfo: true
        },

        plugins: [
            require("karma-webpack"),
            require("istanbul-instrumenter-loader"),
            require("karma-mocha"),
            require("karma-coverage"),
            require("karma-phantomjs-launcher"),
            require("karma-spec-reporter"),
            require("karma-chai-plugins"),
            require("karma-sourcemap-loader")
        ],

        browsers: ['PhantomJS']
    });
};

this is my tests.webpack.js:

// require all `project/test/src/components/**/index.js`
const testsContext = require.context('./lib/', true, /*.js$/);

testsContext.keys().forEach(testsContext);

Example of home.config.js:

import Home from './home.html';
import RightMenu from '../rightMenu/rightMenu.html';

class HomeConfig {
    static initRoute($stateProvider) {
        'ngInject';
        $stateProvider.state('home', {
            url: '/home',
            views: {
                mainView: {
                    templateUrl: Home,
                    controller: 'homeController as home'
                },
                rightMenuView: {
                    templateUrl: RightMenu,
                    controller: 'rightMenuController'
                }
            }
        });
    }
}

export default HomeConfig.initRoute;

What's wrong ? Thank you :)

[3.0.0-beta] query.substr is not a function

Tried installing 3.0.0-beta to see if it would get rid of the parseQuery warning, and instead I'm getting this error for every file:

ERROR in ./src/helpers/promise.ts
Module build failed: TypeError: query.substr is not a function
    at Object.parseQuery (/Users/dpogue/Coding/project/node_modules/loader-utils/lib/parseQuery.js:12:11)
    at Object.exports.default (/Users/dpogue/Coding/project/node_modules/istanbul-instrumenter-loader/dist/index.js:17:43)
 @ ./src/helpers/promise.spec.ts 3:0-49
 @ ./src .spec.ts$
 @ ./webpack.tests.js

update readme to webpack2

hi,

i see the readme instructions refers still at webpack1.
it would be nice to update it in order to support the latest version of webpack. [that now it's stable]

Istanbul throws when pitching loader is used

When using a pitching loader such as:
https://github.com/walmartlabs/circus-handlebars#programatically-loading-modules
https://github.com/walmartlabs/circus-handlebars/blob/master/lib/loaders/helper.js

Istanbul fails to report coverage properly due to resourcePath having the same value for both the original request, require('helper!foo'), and the request made by the pitching loader, require('!foo').

I could not find a way to generically prevent the coverage tool from running on the code emitted by the pitching loader and had to use require('!!helper!foo') to fix the coverage reporting.

requires need to have assignments to variables for the files to be picked up

This works and instrumenter picks up the about-ctrl.js because I assigned it to the variable AboutCtrl:

'use strict';

var angular = require('angular');
var AboutCtrl = require('./about-ctrl.js');
var template = require('./template.html');

module.exports = function() {
    angular.module('about', [require('angular-ui-router')])
        .config(['$stateProvider', function($stateProvider) {
            $stateProvider
                .state('about', {
                    url: '/about',
                    template: template,
                    controller: AboutCtrl,
                    controllerAs: 'ctrl'
                });
        }]);
};

However, this doesn't work, because the about-ctrl.js wasn't assigned to a variable, so it is not getting picked up by the coverage report:

'use strict';

var angular = require('angular');

module.exports = function() {
    angular.module('about', [require('angular-ui-router')])
        .config(['$stateProvider', function($stateProvider) {
            $stateProvider
                .state('about', {
                    url: '/about',
                    template: require('./template.html'),
                    controller: require('./about-ctrl.js'),
                    controllerAs: 'ctrl'
                });
        }]);
};

Also, I'd like to mention that I want coverage for all files, even untested ones. That's why my config looks like this:

'use strict';

var path = require('path');
var webpack = require('webpack');
var webpackConfig = require(path.join(__dirname, '/webpack.config.js'));

module.exports = function(config) {
    config.set({
        basePath: __dirname,

        files: [
            'public/js/main.js',
            'public/js/**/tests/*.test.js'
        ],

        preprocessors: {
            'public/js/main.js': ['webpack', 'sourcemap'],
            'public/js/**/tests/*.test.js': ['webpack', 'sourcemap']
        },

        webpack: webpackConfig,

        webpackMiddleware: {
            stats: {
                colors: true
            }
        },

        reporters: ['spec', 'coverage'],

        coverageReporter: {
            reporters: [
                { type: 'html', dir: 'coverage/' },
                { type: 'text-summary' }
            ]
        },

        port: 9999,

        colors: true,

        logLevel: config.LOG_INFO,

        frameworks: ['jasmine'],

        browsers: ['PhantomJS'],

        captureTimeout: 60000,

        singleRun: true,

        plugins: [
            require('karma-webpack'),
            require('karma-jasmine'),
            require('karma-spec-reporter'),
            require('karma-chrome-launcher'),
            require('karma-sourcemap-loader'),
            require('karma-phantomjs-launcher'),
            require('karma-coverage')
        ]
    });
};

Support for spread operator and decorartors

Hi,

I'm trying to get code coverage with instanbul. I am using karma and webpack.

In my code base I am using es2015 plus some other features like decorators. So I am setting esModules to true. This is my webpack loader settings for istanbul-instrumenter-loader.

{
            test: /\.js$/,
            use: {
              loader: 'istanbul-instrumenter-loader',
              query: { esModules: true }
            },
            include: path.resolve('src/')
          }

When I run karma, I am getting errors like the following:

ERROR in index.js
Module build failed: SyntaxError: Unexpected token (13:2)

These errors are due to the use of spread operator or the decortator in js.

Things like this:

    analyticsEvents.push({
          ...data,
          event,
          eventCallback
        });
  @bindable columnId;
  @bindable columnLabel;
  @bindable onColumnSorted;

I understand the decorator syntax or the spread operator are not part of es2015.

This why I am using this settings in my .babelrc:

{
  "presets": ["es2015", "stage-0"],
  "plugins": ["transform-decorators-legacy"]
}

Is istanbul-instrumenter-loader reading the babel settings or is it independ of that? Maybe there is some config setting I am missing?
Any idea how I can make this work?

Covering or Ignoring Generated Functions

Hi,

I have a setup using Webpack with Babel and this project, and while everything works great, one issue I've been trying to figure out how to fix is the coverage occurring on the generated functions.

Functions such as _createClass and _classCallCheck end up tanking my coverage stats, especially for Branches.

Is there something I may have done incorrectly? Is there a way to ignore these generated functions from being covered? Is this on a roadmap anywhere for resolution?

Thanks!

fixWebpackSourcePaths without karma

In the README you have the karma config with fixWebpackSourcePaths. I'm not using karma and I have the problem that the paths are wrong (all loader prependend).

How can I use this option without karma?
I tried nyc config and webpack loader options

license?

WTFPL. lol

So is there a real license agreement to this? I'm trying to get this package approved for usage and our legal team will probably have a fit about it.

I can PR and update your license if you require.

Getting error while running test with karma

Hi,

I am getting below error while running test with karma, I am using angular 2 webpack starter configuration. Please help me resolving the issue.

23 05 2017 17:34:06.818:WARN [reporter]: SourceMap position not found for trace: undefined
Chrome 50.0.2661 (Windows 10 0.0.0) ERROR
Uncaught Error: Module build failed: SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (1:0)
at Parser.pp$5.raise (S:\projects\trunk\util_angular2\node_modules\babylon\lib\index.js:4452:13)
at Parser.pp$1.parseStatement (S:\projects\trunk\util_angular2\node_modules\babylon\lib\index.js:1881:16)
at Parser.parseStatement (S:\projects\trunk\util_angular2\node_modules\babylon\lib\index.js:5804:22)
at Parser.pp$1.parseBlockBody (S:\projects\trunk\util_angular2\node_modules\babylon\lib\index.js:2268:21)
at Parser.pp$1.parseTopLevel (S:\projects\trunk\util_angular2\node_modules\babylon\lib\index.js:1778:8)
at Parser.parse (S:\projects\trunk\util_angular2\node_modules\babylon\lib\index.js:1673:17)
at Object.parse (S:\projects\trunk\util_angular2\node_modules\babylon\lib\index.js:7180:37)
at Instrumenter.instrumentSync (S:\projects\trunk\util_angular2\node_modules\istanbul-lib-instrument\dist\instrumenter.js:121:31)
at Instrumenter.instrument (S:\projects\trunk\util_angular2\node_modules\istanbul-lib-instrument\dist\instrumenter.js:176:32)
at Object.module.exports (S:\projects\trunk\util_angular2\node_modules\istanbul-instrumenter-loader\index.js:25:25)
at config/spec-bundle.js:69575

Thanks

istanbul-lib-instrument v1.3.1 breaking change

The istanbul-lib-instrument last release (v1.3.1) affected the istanbul-instrumenter-loader package with the error message (No changes in my codebase):

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
SyntaxError: Cannot declare a parameter named 'area' in strict mode

Removed the package from postLoaders in Webpack configuration.

Was working perfectly on istanbul-lib-instrument v1.3.0 release

Transpiled sources

I got this working, but the coverage is showing my transpiled sources. I've spent hours trying to figure out which modules to use to get the ES6 code to be shown by Istanbul.

Do I need something like isparta-loader? I tried plugging it in as a preLoader, but no dice.

My karma.config

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

        // use headless PhantomJS
        browsers: ['Chrome'],

        // use Jasmine with Sinon for mocking and stubs
        frameworks: ['jasmine', 'sinon'],

        // load our single entry point for our tests
        files: [
            'tests/tests.webpack.js'
        ],

        // preprocess with webpack and our sourcemap loader
        preprocessors: {
            'tests/tests.webpack.js': ['webpack', 'sourcemap']
        },

        reporters: [
            // https://github.com/mlex/karma-spec-reporter
            'spec',

            // https://github.com/karma-runner/karma-coverage
            'coverage'
        ],


        // configure webpack within Karma
        webpack: {

            // just do inline source maps instead of the default
            devtool: 'inline-source-map',

            module: {
                loaders: [{
                    test: /\.js/,
                    exclude: /node_modules/,
                    loader: 'babel-loader'
                }, {
                    test: /\.html$/,
                    loader: 'html'
                }],
                // delays coverage til after tests are run, fixing transpiled source coverage error
                postLoaders: [{
                    test: /\.js$/,
                    exclude: /(tests|node_modules|\.spec\.js$)/,
                    loader: 'istanbul-instrumenter'
                }]
            }
        },

        // configure the webpack server to not be so verbose
        webpackServer: {
            noInfo: true
        },

        // setup code coverage
        coverageReporter: {
            reporters: [{
                type: 'text-summary',
            }, {
                type: 'html',
                dir: 'coverage/'
            }]
        },


    });
};

My tests.webpack.js is my single entry point.

var context = require.context('../src', true, /\.js$/);
context.keys().forEach(context);

webpack-defaults upgrade

Addition of webpack-defaults & associated refactoring as a part of the next Major release

Issue exists for status tracking across the organization.

Please do not close

Tests in same directory as source incorrect coverage

I had coverage set up just fine when my tests were in their own directory but I've now moved tests alongside my source code and the coverage is all wrong.

I have done this:

const testsContext = require.context('../../src', true, /\.test\.js$/);
testsContext.keys().forEach(testsContext);

and have verified that the keys are only of.test.js files yet coverage is still reporting on the test files themselves. Would you happen to know why this happens? Is it an issue with require.context, the loader or Istanbul itself? Thanks!

Sourcemaps not tracing back to the source

The sourcemaps that istanbul-instrumenter-loader returns are not using the input sourcemap to provide sourcemaps back to the source.

This can be reproduced in the tests for this repo.

  • modify the 'sourcemap files on by default' test in test/index.test.js to print the sources content:
  // ...
  const sourceMap = stats.compilation.assets['main.js.map'].source();
  console.log(JSON.parse(sourceMap).sourcesContent)
  // ...
  • npm run test
  • you should see the below printed:
[ '"use strict";\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }\n\nmodule.exports = function () {\n  function Foo() {\n    _classCallCheck(this, Foo);\n  }\n\n_createClass(Foo, [{\n    key: "bar",\n    value: function bar() {\n      return !!this;\n    }\n  }]);\n\n  return Foo;\n}();\n\n\n// WEBPACK FOOTER //\n// /fixtures/basic.js' ]
  • this is how it looks formatted:
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

module.exports = function () {
    function Foo() {
      _classCallCheck(this, Foo);
  }

_createClass(Foo, [{
      key: "bar",
    value: function bar() {
        return !!this;
    }
  }]);

  return Foo;
}();


// WEBPACK FOOTER //
// /fixtures/basic.js
  • which is quite different from the original source (tests/fixtures/basic.js):
module.exports = class Foo {
  bar() {
    return !!this;
  }
};

I tried tracing this around for a bit and couldn't find where it goes wrong, but it seems that the instrumenter is receiving the input sourcemap but instrumenter.lastSourceMap() isn't a sourcemap back to the source.

Nothing appears in the reporting folder

Hello,
I tried to use it, but doesn't appears in in the reporting folder.
This is my configuration:

'use strict';

var path = require('path');
var webpack = require('webpack');

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

        plugins: [
            'karma-webpack',
            'karma-jasmine',

            //'karma-coverage',
            //'karma-htmlfile-reporter',
            'istanbul-instrumenter-loader',

            'karma-chrome-launcher',
            'karma-phantomjs-launcher',
        ],
        // base path, that will be used to resolve files and exclude
        basePath: '',

        // testing framework to use (jasmine/mocha/qunit/...)
        frameworks: ['jasmine'],

        preprocessors: {
            'src/**/*.js': ['webpack']
        },

        reporters: ['progress', 'coverage'],

        // list of files / patterns to load in the browser
        files: [
            'node_modules/jquery/dist/jquery.js',
            'node_modules/phaser/dist/phaser-arcade-physics.js',
            'node_modules/phaser-debug/dist/phaser-debug.js',
            'src/**/*.spec.js'
        ],

        webpack: {
            // karma watches the test entry points
            // (you don't need to specify the entry option)
            // webpack watches dependencies

            // webpack configuration
            cache: false,
            //entry: entries,
            context: path.join(__dirname, 'src'),
            module: {
                loaders: [{
                    test: /\.js$/i,
                    exclude: /node_modules/i,
                    loader: 'traceur?experimental&arrayComprehension&runtime'
                }, {
                    test: /(phaser-arcade-physics|phaser-debug|jquery|query.signalR.min)\.js$/i,
                    loader: 'script'
                }, {
                    test: /\.json$/i,
                    exclude: /\.audiosprite\.json$/i,
                    loader: 'json'
                }, {
                    test: /\.css$/i,
                    loader: 'style!css'
                }, {
                    test: /\.less$/i,
                    loader: 'style!css!less'
                }, {
                    test: /\.(jpe?g|png|gif)$/i,
                    loader: 'file?name=[path][name].[ext]?[hash]'
                }, {
                    test: /\.(mp3|ac3|ogg|m4a)$/i,
                    loader: 'file?name=[path][name].[ext]?[hash]'
                }, {
                    test: /\.(ttf|woff|eot)$/i,
                    loader: 'file?name=[path][name].[ext]?[hash]'
                }, {
                    test: /\.audiosprite\.json$/i,
                    loader: 'file?name=[path][name].[ext]?[hash]'
                }],
                postLoaders: [{ // << add subject as webpack's postloader
                    test: /\.js$/,
                    loader: 'istanbul-instrumenter'
                }]
            },
            node: {
                console: true
            },
            resolve: {
                alias: {
                    'jquery': path.join(__dirname, 'node_modules/jquery/dist/jquery.js'),
                    'signalr': path.join(__dirname, 'src/common/jquery.signalR.min.js'),
                    'phaser': path.join(__dirname, 'node_modules/phaser/dist/phaser-arcade-physics.js'),
                    'phaser-debug': path.join(__dirname, 'node_modules/phaser-debug/dist/phaser-debug.js')
                },
                extensions: ['', '.js']
            },
            plugins: [
                new webpack.ProvidePlugin({
                    Promise: 'bluebird',
                    signalr: 'signalr'
                })
            ]
        },

        webpackServer: {
            // webpack-dev-server configuration
            // webpack-dev-middleware configuration
            // i. e.
            noInfo: false,
            stats: {
                colors: true
            }
        },

        // the port used by the webpack-dev-server
        // defaults to 'config.port' + 1
        //webpackPort: 1234,


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

        // web server port
        port: 8080,

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


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


        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['PhantomJS'],


        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false,

        // optionally, configure the reporter
        coverageReporter: {
            type: 'html',
            dir: 'reports/coverage'
        },

        htmlReporter: {
            outputFile: 'reports/tests/units.html'
        }
    });
};

Did I do a mistake?

Help ! Dont work in my case.

Hi !

I have the following structure :

├── app/
│   └──  scripts/
│       ├── modules/
│       │      └── foo/
│       │         └── index.js
│       └── app.js
└── test/
    ├── spec/
    │  └── modules/
    │       └── foo/
    │           └── index.js
    └── karma.conf.js

And my config looks like this :

module.exports = function (config) {
  config.set({
    // basePath, frameworks ....
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine',
      'karma-coverage',
      'karma-tap-reporter'
    ],
    files: [
      // Dependencies
      'test/spec/*.js',
      'test/spec/modules/**/*.js',
    ],
    preprocessors: {
      'app/scripts/app.js': ['webpack', 'sourcemap', 'coverage'],
      'app/scripts/modules/**/*': ['coverage'],
      'test/spec/*.js': ['babel'],
      'test/spec/modules/**/*.js': ['babel']
    },
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine',
      'karma-coverage',
      'karma-sinon-chai',
      'karma-tap-reporter',
      'karma-babel-preprocessor',
      'karma-coffee-preprocessor',
      'karma-sourcemap-loader',
      require("karma-webpack")
    ],
    webpack: {
      module: {
        postLoaders: [
          { test: /\.js$/, loader: 'istanbul-instrumenter' }
        ],

        loaders: [
          // JS
          { test: /\.js?$/, exclude: /node_modules/, loader: 'babel-loader' }
        ]
      }
    },
    // Coverage reporters, babel preprocessor ...
  });
}

I tried to put istanbul-instrumenter as preLoader and postLoader but it never works for me.

In preLoader, my tests fail, and in postLoader, I have the following error.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

Any idea ?

PS : My coverage worked good before webpack migration and all of my tests pass without preLoader istanbul instrumenter.

Thanks

Set up for ES6 project

Is there any solution for projects using ES6 syntax? The problem is that it doesn't seem possible doing that require matching all test files and tested files.

Webpack: Coverage shows in production build

I generate my build with grunt. The task look like this:

grunt.registerTask('build', [
  'karma:unit',
  'webpack:build'
]);

So what happens is that all tests run and for coverage-support I add the instrumenter as a preLoader:

webpackConfig.module.preLoaders = [
    {
        test: /\.js$/,
        include: path.resolve('app/'),
        loader: 'istanbul-instrumenter'
    }
];

This works fine for me. So far, so good.
After this task finished and webpack:build is running, in which the preLoader is not even preset, the compiled source still shows the coverage like

var t = Function("return this")();
        t.__coverage__ || (t.__coverage__ = {}), t = t.__coverage__, t["/Users/name/src/project/app/entry.js"] || (t["/Users/name/src/project/app/entry.js"] = {
            path: "/Users/name/src/project/app/entry.js",
            s: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0 },
            b: {
                1: [
                    0,
                    0
                ]
            },
            f: { 1: 0, 2: 0 },
            fnMap: { 1: { name: "(anonymous_1)", line: 5, loc: { start: { line: 5, column: 34 }, end: { line: 5, column: 53 } } }, 2: { name: "(anonymous_2)", line: 13, loc: { start: { line: 13, column: 54 }, end: { line: 13, column: 73 } } } },
            statementMap: { 1: { start: { line: 1, column: 0 }, end: { line: 1, column: 26 } }, 2: { start: { line: 3, column: 0 }, end: { line: 3, column: 25 } }, 3: { start: { line: 5, column: 0 }, end: { line: 23, column: 18 } }, 4: { start: { line: 6, column: 4 }, end: { line: 6, column: 44 } }, 5: { start: { line: 7, column: 4 }, end: { line: 7, column: 50 } }, 6: { start: { line: 8, column: 4 }, end: { line: 8, column: 52 } }, 7: { start: { line: 10, column: 4 }, end: { line: 10, column: 50 } }, 8: { start: { line: 13, column: 4 }, end: { line: 22, column: 30 } }, 9: { start: { line: 14, column: 8 }, end: { line: 14, column: 49 } }, 10: { start: { line: 16, column: 8 }, end: { line: 18, column: 9 } }, 11: { start: { line: 17, column: 12 }, end: { line: 17, column: 24 } }, 12: { start: { line: 20, column: 8 }, end: { line: 20, column: 27 } }, 13: { start: { line: 25, column: 0 }, end: { line: 25, column: 33 } } },
            branchMap: {
                1: {
                    line: 16,
                    type: "if",
                    locations: [
                        { start: { line: 16, column: 8 }, end: { line: 16, column: 8 } },
                        { start: { line: 16, column: 8 }, end: { line: 16, column: 8 } }
                    ]
                }
            },
            code: [
                "var $ = require('jquery');",
                "",
                "var defer = $.Deferred();",
....etc

This will not happen if I never add the instrumenter as a preLoader.
Why is it still present in my build task even though the webpack.config does not contain it?

Pass "noCompact" option

Is there a way to specify a query, similar to other loaders, where I could tell the instrumenter to use the istanbul "noCompact" option?

Similar to:

    {
        test: /\.js?$/,
        exclude: /node_modules/,
        loader: 'istanbul-instrumenter',
        query: {
            instrumenterOptions: {
                istanbul: { noCompact: true }
            }
        }
    }

or as a stringified query on the loader string itself?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.