Angular 1.x、ES5/ES6 并使用 Karma 进行测试

Angular 1.x, ES5/ES6 and testing with Karma

我有一个 angular 应用程序(混合了 ES5 和 ES6 文件),我正在为其开发测试。 我使用带有这些选项的 babel CLI 转译的 ES6 文件 --modules system --module-ids。 假设我有这样的事情:

ES5 文件:

angular.module('app').controller('A', function($scope) {
    ...
});

ES6 文件:

export class B {
    constructor($scope) {
        this.$scope = $scope 
    }

   ...
}

我有一个名为 boot.js 的文件:

import {B} from 'controllers/B';

angular.module('app').controller('B', B);

在我的页面上,我导入了引导文件(使用 es6-module-loader)和 bootstrap angular 应用程序:

System.import('boot').then(function() {
    angular.bootstrap(document, ['app']);
});

现在,我假设我需要做一些类似于业力测试的事情 - 我需要在 运行 我的测试之前加载我的 boot.js。 我解决问题的方法是在我的测试文件中调用 System.impot('boot') - 但似乎不正确:

'use strict';

System.import('boot');

describe('Controller: B', function() {
    beforeEach(module('app'));

    var $scope;

    beforeEach(inject(function(_$rootScope_, $controller) {
        scope = _$rootScope_.$new();

        $controller('B', {$scope: $scope); 
    }));

    it('...', function() {

    });
});

有更好的方法吗?

我最终找到的解决方案涉及使用 karma-systemjs

在 systemjs/files 部分包含所有测试文件:

 systemjs: {
     files: [
         // TEST FILES
     ],

     configFile: 'system.config.js',

     config: {
         paths: {
             'angular-mocks': 'node_modules/angular-mocks/angular-mocks.js'
         }
     }
}

并且在测试中而不是使用:

System.import('boot');

使用:

'use strict';

import 'angular-mocks';
import 'angular/boot.js';

describe('Controller: B', function() {
    beforeEach(module('app'));

    var $scope;

    beforeEach(inject(function(_$rootScope_, $controller) {
        scope = _$rootScope_.$new();

        $controller('B', {$scope: $scope); 
    }));

    it('...', function() {

    });
});

希望这对以后的其他人有所帮助。