Karma and CoffeScript and Code Coverage

筅森魡賤 提交于 2019-12-13 04:55:46

问题


I think something may be wrong with the Karma CoffeeScript code coverage preprocessor. Or I'm not sure what I'm doing wrong! So I come to you StackOverflow. Basically I'm trying to setup my karma test suite to give me code coverage in an lcov format so I can ship that off to CodeClimate. I had it so my test suite (used to) work, but now I can't seem to get anything from it except errors. My project is a Rails project and the files are setup to be preprocessed by the asset pipe (ie. name.js.coffee files) but if I include them in the coverage preprocessor it seems to preprocess them just fine, BUT it throws an error on every file. For example, something will be processed to a function and it'll say function is a reserved word, etc. So it still thinks they are coffeescript files I'm guessing and using that syntax appropriately. When I just try to process them using the coffeescript preprocessor though I get coffeescript errors where there shouldn't be any. Help?

Here are the errors:

npm test

> tracktrain@0.1.6 test /Users/bytenel/workspace/tracktrain
> ./node_modules/.bin/karma start --single-run --browsers Firefox

INFO [karma]: Karma v0.12.24 server started at http://localhost:9876/
INFO [launcher]: Starting browser Firefox
ERROR [preprocessor.coverage]: Syntax error on line 7: indentation is ambiguous
4 :     $document.ready(()->
5 :       $scope.loading = false;
6 :     )
7 :   ])
^ :~~~~^
8 : 
9 : 
  at /Users/bytenel/workspace/tracktrain/app/assets/javascripts/controllers/root_controller.js.coffee
ERROR [preprocessor.coverage]: Syntax error on line 66: indentation is ambiguous
63 :                                                        user.selected = false
64 :                                                        $scope.selectedUsers = []
65 :             ]
66 :            )
^^ :~~~~~~~~~~~~^
  at /Users/bytenel/workspace/tracktrain/app/assets/javascripts/controllers/lecture_ctrl.js.coffee
ERROR [preprocessor.coverage]: Syntax error on line 9: indentation is ambiguous
6 :                            user = $resource "/users/:id.json", { id: '@id' }
7 : 
8 :                            user
9 :           ] )
^ :~~~~~~~~~~~~~~^
  at /Users/bytenel/workspace/tracktrain/app/assets/javascripts/factories/user.js.coffee
ERROR [preprocessor.coverage]: Syntax error on line 5, column 1: unexpected '\n' (\u000A)
2 : 
3 : angular.module( 'trackTrainApp' )
4 : .factory( 'OrgTrainUser',
5 :           [ '$resource', ( $resource ) ->
^ :~^
6 :                            user = $resource "/lectures/:id/users.json",
7 :                                             {
8 :                                               id: "@id"
  at /Users/bytenel/workspace/tracktrain/app/assets/javascripts/factories/orgtrainuser.js.coffee
ERROR [preprocessor.coverage]: Syntax error on line 9: indentation is ambiguous
06 :                                                          if $flashNotice[0] && $flashNotice[0].childNodes && $flashNotice[0].childNodes[3].id != 'flash_alert'
07 :                                                            $flashNotice.slideUp animationTime
08 :                                                          return;
09 :                                                       ), 2000;
^^ :~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
10 :    return;)( jQuery );
  at /Users/bytenel/workspace/tracktrain/app/assets/javascripts/flashes.js.coffee
ERROR [preprocessor.coverage]: Syntax error on line 17: indentation is ambiguous
14 :          ajax: $.fn.dataTable.pipeline( {
15 :                                             url: 'lectures/list.json',
16 :                                             pages: 5
17 :                                           }),
^^ :~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
18 :          columns: [
19 :            { data: 'name' },
20 :            { data: 'start_date' },
  at /Users/bytenel/workspace/tracktrain/app/assets/javascripts/lectures.js.coffee
ERROR [preprocessor.coverage]: Syntax error on line 20, column 2: unexpected '(DEDENT)' (\uEFFE)
17 :     return attachmentEntry;
18 : 
19 : 
20 :   $('#add-attachment').on 'click', (event) ->
^^ :~~^
21 :     event.preventDefault
22 :     attachmentEntryCount = $('.attachment-entry').length
23 : 
  at /Users/bytenel/workspace/tracktrain/app/assets/javascripts/training_history.js.coffee
INFO [Firefox 32.0.0 (Mac OS X 10.9)]: Connected on socket dwjoowbAkz3xKEQ4pVCT with id 85121913
WARN [web-server]: 404: /Users/bytenel/workspace/tracktrain/app/assets/javascripts/controllers/lecture_ctrl.js.js
WARN [web-server]: 404: /Users/bytenel/workspace/tracktrain/app/assets/javascripts/factories/user.js.js
WARN [web-server]: 404: /Users/bytenel/workspace/tracktrain/app/assets/javascripts/controllers/root_controller.js.js
WARN [web-server]: 404: /Users/bytenel/workspace/tracktrain/app/assets/javascripts/factories/orgtrainuser.js.js
WARN [web-server]: 404: /Users/bytenel/workspace/tracktrain/app/assets/javascripts/controllers/root_controller.js.js
WARN [web-server]: 404: /Users/bytenel/workspace/tracktrain/app/assets/javascripts/controllers/lecture_ctrl.js.js
WARN [web-server]: 404: /Users/bytenel/workspace/tracktrain/app/assets/javascripts/factories/user.js.js
WARN [web-server]: 404: /Users/bytenel/workspace/tracktrain/app/assets/javascripts/factories/orgtrainuser.js.js
Firefox 32.0.0 (Mac OS X 10.9) ERROR
  SyntaxError: missing ; before statement
  at /Users/bytenel/workspace/tracktrain/spec/javascripts/controllers/leture_ctrl_spec.coffee:1

Firefox 32.0.0 (Mac OS X 10.9) ERROR
  SyntaxError: missing ; before statement
  at /Users/bytenel/workspace/tracktrain/spec/javascripts/factories/org_train_user_factory_spec.coffee:1

Firefox 32.0.0 (Mac OS X 10.9) ERROR
  SyntaxError: missing ; before statement
  at /Users/bytenel/workspace/tracktrain/spec/javascripts/factories/user_factory_spec.coffee:1


npm ERR! weird error 1
npm ERR! not ok code 0

Here is my karma.conf.js file:

// Karma configuration
// Generated on Sat Aug 02 2014 00:12:00 GMT-0600 (MDT)

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

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


        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        plugins: [
            'karma-jasmine',
            'karma-firefox-launcher',
            'karma-coffee-preprocessor',
            'karma-coverage'
        ],

        // list of files / patterns to load in the browser
        // TODO: this is not requiring files correctly, need to fix TR-335
        files: [
            'vendor/assets/javascripts/karma-jasmine/lib/jasmine.js',
            'vendor/assets/javascripts/karma-jasmine/src/adapter.js',
            'vendor/assets/javascripts/angular/angular.js',
            'vendor/assets/javascripts/angular-resource.min.js',
            'vendor/assets/javascripts/angular-mocks/angular-mocks.js',
            'vendor/assets/javascripts/jquery-2.1.1.min.js',
            'vendor/assets/javascripts/jquery.dataTables.min.js',
            'vendor/assets/javascripts/d3/d3.js',
            'vendor/assets/javascripts/nvd3/nv.d3.js',
            'vendor/assets/javascripts/angularjs-nvd3-directives/dist/angularjs-nvd3-directives.js',
            'vendor/assets/javascripts/ui-bootstrap-tpls-0.11.0.min.js',
            'vendor/assets/javascripts/*.*js',
            'spec/javascripts/*_spec.js*',
            'spec/javascripts/**/*_spec.js*',
            'app/assets/javascripts/app.js.coffee',
            'app/assets/javascripts/controllers/root_controller.js.coffee',
            'app/assets/javascripts/controllers/lecture_ctrl.js.coffee',
            'app/assets/javascripts/factories/user.js.coffee',
            'app/assets/javascripts/factories/orgtrainuser.js.coffee',
            {   pattern: 'app/assets/javascripts/*.js.*',
                watched: true,
                included: false,
                served: false },
            'spec/javascripts/**/*_spec.coffee'
        ],


        // list of files to exclude
        exclude: [
            'app/assets/javascripts/application.js.coffee.erb'
        ],


        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'app/**/*.*.coffee': ['coverage']
        },

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

        coverageReporter: {
            type : 'lcovonly',
            dir : 'coverage/',
            subdir: 'javascript'
        },

        'scripts': {
            'test': './node_modules/.bin/karma start --single-run --browsers Firefox'
        },

        // 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: true,


        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Firefox'],


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

And here is an example spec and js file:

describe 'OrgTrainUser', () ->
                           factory = undefined
                           $httpBackend = undefined
                           beforeEach module( 'trackTrainApp' )
                           beforeEach inject( ( $injector ) ->
                                                $httpBackend = $injector.get( '$httpBackend' );
                                                factory = $injector.get( 'OrgTrainUser' );
                                            )
                           it 'queries with username',
                              () ->
                                $httpBackend.expectGET( '/lectures/123/users.json' )
                                .respond( [ {
                                            id: '123',
                                            first_name: 'test',
                                            last_name: 'bob'
                                          } ] )
                                result = factory.query( { id: '123' } )

                                $httpBackend.flush()

                                expect( result[0].id ).toEqual( '123' )

'use strict'

angular.module( 'trackTrainApp' )
.factory( 'OrgTrainUser',
          [ '$resource', ( $resource ) ->
                           user = $resource "/lectures/:id/users.json",
                                            {
                                              id: "@id"
                                            },
                                            {
                                              query:
                                                method: "GET"
                                                isArray: true
                                              show:
                                                method: 'GET'
                                                isArray: true
                                            }

                           user
          ] )

And the related error:

ERROR [preprocessor.coverage]: Syntax error on line 9: indentation is ambiguous
06 :                                                          if $flashNotice[0] && $flashNotice[0].childNodes && $flashNotice[0].childNodes[3].id != 'flash_alert'
07 :                                                            $flashNotice.slideUp animationTime
08 :                                                          return;
09 :                                                       ), 2000;
^^ :~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
10 :    return;)( jQuery );

Could it be related to me using strict mode in these files?


回答1:


Karma code coverage is powered by brick project. brick compiles and instruments the coffeescript code. The compiler used by brick is not the standard coffeescript compiler, instead, brick uses a non 100% compatible compiler called coffeescript-redux

Our project is perfectly compiled by coffeescript 1.8 but has a lot of errors when compiled with redux

The ibrik project and the redux compilers have been relatively inactive in a while, thus we simply forgot our attempts to get the cover of our code. Maybe in a future, with the relaunch of coffeescript-redux, we can use again the karma-code-coverage plugin.

--------- UPDATE --------------

The ibrik project has been updated to use coffescript, but karma-coverage not yet. You can hack your package.json to get it working or wait to karma-coverage fix it, however I have two karma config files in my project, first to run without coverage (fast - 3 seconds) and second to coverage the javascript (little slower - 10 seconds)

Check karma-coverage.conf.coffee

wiredep = require('wiredep')
path = require('path')

module.exports = (config) ->
  config.set
    frameworks: ['jasmine']

    files: wiredep(devDependencies: true)['js'].map (file) ->
      path.relative(process.cwd(), file)
    .concat [
      '.tmp/common/app.js'
      '.tmp/common/services/helpers/**/*.js'
      '.tmp/common/**/*.js'
      '.tmp/app/**/*.js'
      'src/common/**/*.spec.coffee'
      'src/app/**/*.spec.coffee'
      'test/spec/**/*.coffee'
      # directives templates
      'src/common/directives/**/*.html'
      'src/app/components/**/*.html'
      'bower_components/angular-strap/src/**/*.tpl.html'
      # fixtures
      {
        pattern: 'test/fixtures/**/*.json'
        watched: true
        served: true
        included: false
      }
    ]

    exclude: []

    preprocessors:
      'src/app/components/**/*.html': 'ng-html2js'
      'bower_components/angular-strap/src/**/*.tpl.html': 'ng-html2js'
      'src/common/**/*.spec.coffee': 'coffee'
      'src/app/**/*.spec.coffee': 'coffee'
      'test/spec/**/*.coffee': 'coffee'
      '.tmp/**/*.js': 'coverage'

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

    ngHtml2JsPreprocessor:
      stripPrefix: 'src/'

    coverageReporter:
      type: 'html',
      dir: '.tmp/test/coverage/'

    htmlReporter:
      outputDir: '.tmp/test/html/'

    coffeePreprocessor:
      options:
        bare: true
        sourceMap: true
      transformPath: (path) ->
        return path.replace(/.js$/, '.coffee')

    port: 9876
    colors: true
    logLevel: config.LOG_INFO
    autoWatch: true
    browsers: ['PhantomJS']
    singleRun: false



回答2:


I'd look at the following:

https://github.com/karma-runner/karma-coverage/issues/75, see @zeno's comment in particular. There is a forked build that allows karma-coverage to parse standard coffee script. It does this by using a fork of Ibrik by HBOCodeLabs that switches out redux for standard coffeescript. To use you would add the following to your dev dependencies

karma-coverage": "git+https://github.com/kylewelsby/karma-coverage#fix-coffee-script-compiler"

That works for me!



来源:https://stackoverflow.com/questions/26471962/karma-and-coffescript-and-code-coverage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!