karma-runner

How to preserve line correct line numbers with karma-babel-preprocessor and PhantomJs?


When I use the documented configuration of karma-babel-preprocessor like this

module.exports = function (config) {
  config.set({
    preprocessors: {
      'src/**/*.js': ['babel'],
      'test/**/*.js': ['babel']
    },
    babelPreprocessor: {
      options: {
        sourceMap: 'inline'
      },
      filename: function (file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName: function (file) {
        return file.originalPath;
      }
    }
  });
};

I get wrong source line numbers, e.g.

 at /var/www/edu-web/tests/jasmine/services/image/imageServiceTest.es5.js:77

There is no support for source maps by default, so it is no surprise. However, the problem here is that imageServiceTest.es5.js file is deleted after karma finishes so I have no choice but to guess where the unit test fail (on which line) and that's slow.

There is a solution in the issue for Chrome (not PhantomJs). Can I fix my configuration for PhantomJs as well?


Solution

  • I found a solution when looking to the Babel documentation:

    retainLines Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps.

    NOTE: This will obviously not retain the columns.

    (http://babeljs.io/docs/usage/options/)

    My final configuration:

    module.exports = function (config) {
      config.set({
        preprocessors: {
          'src/**/*.js': ['babel'],
          'test/**/*.js': ['babel']
        },
        babelPreprocessor: {
          options: {
            sourceMap: 'inline',
            retainLines: true // NEW LINE
          },
          filename: function (file) {
            return file.originalPath.replace(/\.js$/, '.es5.js');
          },
          sourceFileName: function (file) {
            return file.originalPath;
          }
        }
      });
    };