Karma和CoffeeScript以及代码覆盖率

时间:2014-10-20 17:57:34

标签: javascript ruby-on-rails angularjs coffeescript karma-runner

我认为Karma CoffeeScript代码覆盖预处理器可能有问题。或者我不确定我做错了什么!所以我来找你StackOverflow。基本上我试图设置我的业力测试套件给我一个lcov格式的代码覆盖,所以我可以把它发送到CodeClimate。我有它,所以我的测试套件(曾经)工作,但现在我似乎无法从它得到任何东西,除了错误。我的项目是一个Rails项目,文件设置为由资产管道(即.name.js.coffee文件)预处理,但如果我将它们包含在coverage预处理器中,它似乎预处理它们就好了,但它会引发错误在每个文件上。例如,某些东西将被处理成一个函数,并且它会说函数是一个保留字等等。所以它仍然认为它们是coffeescript文件我正在猜测并正确使用该语法。当我尝试使用coffeescript预处理器来处理它们时,虽然我得到了coffeescript错误,但不应该有任何错误。帮助

以下是错误:

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

这是我的karma.conf.js文件:

// 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
    });
};

这是一个示例规范和js文件:

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
          ] )

相关错误:

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 );

这与我在这些文件中使用严格模式有关吗?

2 个答案:

答案 0 :(得分:2)

我要看以下内容:

https://github.com/karma-runner/karma-coverage/issues/75,请参阅@ zeno的评论。有一个分叉的构建,允许karma-coverage来解析标准的咖啡脚本。它通过HBOCodeLabs使用Ibrik的fork来实现这一点,它将redux转换为标准coffeescript。要使用它,请将以下内容添加到您的开发依赖项

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

这对我有用!

答案 1 :(得分:0)

Karma代码覆盖率由brick项目提供支持。 brick编译并记录coffeescript代码。 brick使用的编译器不是标准的coffeescript编译器,而是brick使用非100%兼容的编译器,称为coffeescript-redux

我们的项目完全由coffeescript 1.8编译,但在使用redux编译时出现了很多错误

ibrik项目和redux编译器在一段时间内相对不活跃,因此我们只是忘记了尝试获取代码的问题。也许在未来,随着coffeescript-redux的重新启动,我们可以再次使用karma-code-coverage插件。

---------更新--------------

ibrik项目已更新为使用coffescript,但尚未覆盖karma-coverage。你可以破解你的package.json让它工作或等待业力覆盖修复它,但我在我的项目中有两个业力配置文件,首先运行没有覆盖(快 - 3秒)和第二覆盖javascript(小慢 - 10秒)

检查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