dimanche 3 janvier 2016

ngUpgrade unit testing with karma, systemjs and angular test-shim

I'm preparing a large project to migrate from ng1 to ng2. Followed the instructions here => http://ift.tt/1m4H8yP

My sanity unit test (no imports, just basic math operations) succeeds (but are executed twice). As soon as I add more files in the karma.conf.js (my app files, managed by systemjs) I get followed error from karma / jasmine for each file:

 TypeError: Unexpected anonymous System.register call.

karam.conf.js

// Karma configuration
// Generated on Sat Jan 02 2016 15:05:49 GMT+0100 (CET)

module.exports = function(config) {

  config.set({

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


    // frameworks to use
    // available frameworks: http://ift.tt/1ft83uu
    frameworks: ['jasmine', 'phantomjs-shim'],


    // list of files / patterns to load in the browser
    files: [

                // ng1 resources
                'bower_components/angular/angular.js',
                'bower_components/angular-animate/angular-animate.js',
                'bower_components/angular-mocks/angular-mocks.js',
                'bower_components/ui-router/release/angular-ui-router.js',

                // ng2 resources
                'node_modules/systemjs/dist/system.src.js',
                'node_modules/systemjs/dist/system-polyfills.js',
                'node_modules/es6-shim/es6-shim.js',
                'node_modules/es6-promise/dist/es6-promise.js',
                'node_modules/angular2/bundles/angular2-polyfills.js',
                'node_modules/angular2/bundles/angular2.dev.js',
                'node_modules/angular2/bundles/upgrade.dev.js',
                'node_modules/rxjs/bundles/Rx.js',
                'node_modules/angular2/bundles/http.dev.js',
                'node_modules/angular2/bundles/testing.dev.js',

                // load test shim for systemjs support
                'tests/shims/karma-test-shim.js',

                // app and test resources
                {pattern: 'app/core/*.js', include: false, watched: true}, //   <= systemjs anonymous register call issue!
                {pattern: 'tests/unit/**/*.spec.js', include: false, watched: true}
    ],


    // list of files to exclude
    exclude: [
    ],

        // proxied base paths
        proxies: {
        },


    // preprocess matching files before serving them to the browser
    // available preprocessors: http://ift.tt/1gyw6MG
    preprocessors: {
                '**/*.js' : ['coverage']
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: http://ift.tt/1ft83KQ
    reporters: ['progress', 'coverage'],

        // config coverage output
    coverageReporter: {
          type  : 'html',
          dir   : 'tests/unit/coverage/'
    },


    // 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: http://ift.tt/1ft83KU
    browsers: ['PhantomJS'],


        // plugins
        plugins: [
                'karma-jasmine',
                'karma-coverage',
                'karma-phantomjs-launcher',
                'karma-chrome-launcher',
                'karma-phantomjs-shim'
        ],


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

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity

  });

}

core.controller.tree.ts

/**
 * CORE CONTROLLER TREE
 *
 * @desc        tree controller of core module
 * @date        2015-10-30
 * @version     2
 */



'use strict';



// ---------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------- //



interface ITreeController {

        tree    :    any[];
        types   :    any[];
        q               :    string;

}



// ---------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------- //



export class TreeController implements ITreeController {

        // properties
        public types    :       any[];
        public q                :       string;



        /**
         * constructor
         *
         * @desc        constructor
         * @param       $stateParams    -       any             -       state params
         * @param       tree                    -       any             -       tree items
         * @return      {Tree}
         * @ngInject
         */
        constructor(private $stateParams : any, public tree : any) {

                // assign DI values
                this.q          =       $stateParams.q;
                this.types      =       $stateParams.types;

        }

}

core.controller.tree.js (ts compiled)

/**
 * CORE CONTROLLER TREE
 *
 * @desc        tree controller of core module
 * @date        2015-10-30
 * @version     2
 */
'use strict';
System.register([], function(exports_1) {
    var TreeController;
    return {
        setters:[],
        execute: function() {
            // ---------------------------------------------------------------------------------- //
            // ---------------------------------------------------------------------------------- //
            TreeController = (function () {
                /**
                 * constructor
                 *
                 * @desc        constructor
                 * @param       $stateParams    -       any             -       state params
                 * @param       tree                    -       any             -       tree items
                 * @return      {Tree}
                 * @ngInject
                 */
                function TreeController($stateParams, tree) {
                    this.$stateParams = $stateParams;
                    this.tree = tree;
                    // assign DI values
                    this.q = $stateParams.q;
                    this.types = $stateParams.types;
                }
                return TreeController;
            })();
            exports_1("TreeController", TreeController);
        }
    }
});
//# sourceMappingURL=core.controller.tree.js.map

tsconfig.json

{
  "compilerOptions": {
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "ES5",
    "experimentalDecorators": true,
    "emitDecoratorMetadata" : true,
    "removeComments": false
  },
  "exclude": [
    "bower_components",
    "node_modules"
  ]
}

tests/shims/karma-test-shim.js

/**
 * ANGULAR2 TEST SHIM
 *
 * @desc        test shim for angular2 using systemjs as module loader
 * @date        2016-01-02
 * @version     1.0.0
 */



'use strict';




// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};
System.config({
        packages: {
                'base/app': {
                        defaultExtension: false,
                        format: 'register',
                        map: Object.keys(window.__karma__.files).
                        filter(onlyAppFiles).
                        reduce(function createPathRecords(pathsMapping, appPath) {
                                // creates local module name mapping to global path with karma's fingerprint in path, e.g.:
                                // './hero.service': '/base/src/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
                                var moduleName = appPath.replace(/^\/base\/app\//, './').replace(/\.js$/, '');
                                pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath];
                                console.log(pathsMapping);
                                return pathsMapping;
                        }, {})
                }
        }
});
System.import('angular2/src/platform/browser/browser_adapter').then(function(browser_adapter) {
        browser_adapter.BrowserDomAdapter.makeCurrent();
}).then(function() {
        return Promise.all(
                Object.keys(window.__karma__.files) // All files served by Karma.
                        .filter(onlySpecFiles)
                        .map(function(moduleName) {
                                // loads all spec files via their global module names
                                console.info('spec loaded: ' + moduleName);
                                return System.import(moduleName);
                        }));
}).then(function() {
        __karma__.start();
}, function(error) {
        __karma__.error(error.stack || error);
});
function onlyAppFiles(filePath) {
        return /^\/base\/app\/.*\.js$/.test(filePath)
}
function onlySpecFiles(path) {
        return /\.spec\.js$/.test(path);
}

my file structure

root
 |- app
 |   |- core
 |   |- ...
 |- tests
 |    |- unit
 |    |- e2e
 |    |- shims
 |- node_modules
 |- bower_components
 |- index.html

the app it self works when I call it over the browser. but not when I try to run tests against it. thank you very much for any hints!

Aucun commentaire:

Enregistrer un commentaire