【问题标题】:Angular 1.x, ES5/ES6 and testing with KarmaAngular 1.x、ES5/ES6 和 Karma 测试
【发布时间】:2015-07-02 11:42:42
【问题描述】:

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

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)并引导 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() {

    });
});

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: javascript angularjs karma-runner es6-module-loader


    【解决方案1】:

    我最终找到的解决方案涉及使用 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() {
    
        });
    });
    

    希望这将在未来对其他人有所帮助。

    【讨论】:

    • 我正在进行类似的设置,但无论我是否使用minimatch patterns,Karma 似乎都不会加载 files 数组中的文件。除此之外,我的 karma.config.js 看起来和你的很相似。
    • systemjs: { // Path to your SystemJS configuration file configFile: 'test/unit/system-test.config.js', files: [ 'test/unit/modules/security/security.spec.js' ], // includeFiles: [ // 'dist/js/libs.js', // 'dist/js/app.js', // 'dist/js/app.typescript.js', // 'test/unit/old_js/**/*.spec.js' // ], config: { paths: { 'angular-mocks': 'bower_components/angular-mocks/angular-mocks.js' } } }
    猜你喜欢
    • 2016-02-28
    • 2016-02-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    相关资源
    最近更新 更多