Angular and ES6: Karma Testing with SystemJS

2019-09-16 19:28发布

问题:

Afternoon all, I have a MEAN stack app that I am developing tests for. The Angular code is written using ES6 so I have been trying to configure Karma and SystemJS with Babel as the transpiler to run my tests. Currently, when I karma start karma.conf.js the browser fires up, hangs—as in I cannot click debug or anything else—, and then the browser closes with the console error:

Uncaught TypeError: Cannot set property 'mock' of undefined.

The last line before this is DEBUG [web-server]: serving (cached): ( ... )

My current application structure works like this:

I have all of my module imported into one file app.js where they are injected into my app module:

import HomeController from './components/home/home.js';
import HomeService from './services/homeservice.js';
import HomeDirective from './directives/homedirective.js';
import DifferentController from './components/different/different.js';

// ### Filters
import slugifyFilter from './filters/slugify.js';

var moduleName = 'app';

angular.module(moduleName, ['ngNewRouter', 'ngMock', 'ngAnimate', 'ui.bootstrap', 'slugifyFilter'])

  .config(['$componentLoaderProvider', SetTemplatesPath])
  .controller('AppController', ['$router', AppController]);



function SetTemplatesPath ($componentLoaderProvider){

  $componentLoaderProvider.setTemplateMapping(name => `components/${name}/${name}.html`);
}

function AppController ($router) {

  $router.config([

    // Component is just a template + controller
    // in 'components' folder
    { path: '/', redirectTo: '/home' },
    { path: '/home', component: 'home' },
    { path: '/different/:id', component: 'different' }
  ]);
}

export default moduleName;

I use manual Angular bootstrapping in my index.html file as so:

import { default as AppModule } from './app.js';

angular.bootstrap(document, [ AppModule ]);

try {

   $(document.body).attr("ng-app", "app");

} catch(e){};

I have Karma and SystemJS configured as so:

// Karma configuration
// Generated on Tue Jul 07 2015 19:56:15 GMT-0400 (Eastern Daylight Time)

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

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


    files : [],


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


    plugins : ['karma-systemjs', 'karma-jasmine', 'karma-chrome-launcher', 
                'karma-firefox-launcher', 'karma-ie-launcher' ],

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

    systemjs : {

        // Path to SystemJS config file
        //configFile : 'public/system.conf.js',

        // File patterns for application code, dependencies, and test suites
        files : [

            'public/bower_components/jquery/dist/jquery.js',
            'public/bower_components/angular/angular.js',
            'public/bower_components/angular-mocks/angular-mocks.js',
            'public/bower_components/angular-animate/angular-animate.js',
            'public/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
            'public/bower_components/angular-new-router/dist/router.es5.js',
            'public/bower_components/angular-messages/angular-messages.js',
            'public/**/*.js'
        ],

        // SystemJS configuration specifically for tests, added after your config file. 
        // Good for adding test libraries and mock modules 
        config: {

            baseURL : '/',

            // Set path for third-party libraries as modules
            paths : {

                'jquery': 'public/bower_components/jquery/dist/jquery.js',
                'angular-mocks': 'public/bower_components/angular-mocks/angular-mocks.js',
                'angular' : 'public/bower_components/angular/angular.js',
                'angular-animate' : 'public/bower_components/angular-animate/angular-animate.js',
                'ui-bootstrap' : 'public/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
                'router' : 'public/bower_components/angular-new-router/dist/router.es5.js',
                'angular-messages' : 'public/bower_components/angular-messages/angular-messages.js',
                'babel': 'node_modules/babel-core/browser.js',
                'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js',
                'systemjs': 'node_modules/systemjs/dist/system.js',
                'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js'
            },

            transpiler: 'babel'
        },

        // Specify the suffix used for test suite file names.  Defaults to .test.js, .spec.js, _test.js, and _spec.js 
        testFileSuffix: '-spec.js'
    },


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


    // 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_DEBUG,


    // 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: ['Chrome'],


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

I have a filter here that I am trying to test:

let moduleName = 'slugifyFilter';

angular.module(moduleName, [])
    .filter('slugify', () => {

    return (input) => {

        input = input || '';

        return input.replace(/ /g, '-').toLowerCase();
    };
});

export default moduleName;

And my test file:

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

describe('slugify filter', function() {

    beforeEach(function() {

        angular.mock.module('app');
    });

    beforeEach(angular.mock.inject(function(_$filter_) {

        var $filter = _$filter_;
    }));

    it('returns a slug when given a string', function() {

        var slugify = $filter('slugify');

        expect(slugify('Home Component 3')).toContain('home-component-3');
    });
});

Yet whenever I try to run the tests I get the error described above. What really bothers me is that the browser freezes before the window says 'browser executing.' Any help would be really appreciated, I really want to write some unit tests for my code!

回答1:

Add these files to the karma.files array:

'public/bower_components/jquery/dist/jquery.js',
'public/bower_components/angular-mocks/angular-mocks.js',
'public/bower_components/angular/angular.js'