使用karma,systemjs和angular test-shim进行ngUpgrade单元测试

时间:2016-01-03 15:21:48

标签: angularjs unit-testing angular systemjs typescript1.6

我准备一个大项目从ng1迁移到ng2。按照这里的说明=> https://angular.io/docs/ts/latest/guide/upgrade.html

我的理智单元测试(没有导入,只是基本的数学运算)成功(但执行两次)。一旦我在karma.conf.js(我的app文件,由systemjs管理)中添加更多文件,我就会从每个文件的karma / jasmine中得到错误:

 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: https://npmjs.org/browse/keyword/karma-adapter
    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: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
		'**/*.js' : ['coverage']
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    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: https://npmjs.org/browse/keyword/karma-launcher
    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

  });

}
&#13;
&#13;
&#13;

core.controller.tree.ts

&#13;
&#13;
/**
 * 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;

	}

}
&#13;
&#13;
&#13;

core.controller.tree.js(ts编译)

&#13;
&#13;
/**
 * 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
&#13;
&#13;
&#13;

tsconfig.json

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

测试/垫片/果报测试shim.js

&#13;
&#13;
/**
 * 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);
}
&#13;
&#13;
&#13;

我的文件结构

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

当我通过浏览器调用它时,它自己运行的应用程序。但是当我尝试对它进行测试时却没有。非常感谢您的任何提示!

0 个答案:

没有答案