首页 文章

使用Angular2进行Karma测试:意外的匿名System.register调用

提问于
浏览
4

当我在Angular2中运行Karma Tests时,我收到以下错误 .

未捕获的TypeError:意外的匿名System.register调用 . 在http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?38538ebca96bc7b222f7e7ba15943f173a485f6e:2885

我想是因为var系统目前无法使用 . 即使它实际装载 . 有谁知道为什么这不起作用?

这是我的精简配置:

C:\项目\ karma.conf.js

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'node_modules/systemjs/dist/system.src.js',
      'node_modules/angular2/bundles/angular2.dev.js',
      'tests/**/*Spec.js'
    ],
    exclude: [
    ],
    preprocessors: {
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: ['Chrome', 'Firefox'],
    singleRun: false,
    concurrency: Infinity
  })
}

C:\ project \ tests \ MyTestSpec.ts这一行足以触发错误 .

import {describe, expect, it, xit, inject, beforeEachProviders} from 'angular2/testing';

渲染到C:\ project \ tests \ MyTestSpec.js并在第一次出现系统时产生错误

System.register([], function(exports_1) {
    return {
        setters:[],
        execute: function() {
        }
    }
});
//# sourceMappingURL=CmiCloudSpec.js.map

C:\项目\ tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "watch": true,
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

C:\项目的\ src \ node_modules

包含文件夹angular2和systemjs以及karma,karma-jasmine,jasmine-core和typescript

3 回答

  • 1

    问题是您应该将所有测试文件直接包含在 karma.conf.jsfiles 属性中的Karma中 . 因为您没有在tsc配置中定义 outFile 属性(并且在编译的JS文件中指定了's fine here), the name of modules aren't) .

    您需要创建一个 karma-test-shim.js 文件(将包含该文件)并配置SystemJS以按文件名加载模块并使用 System.import 导入这些文件 .

    以下是 karma-test-shim.js 文件的示例:

    Error.stackTraceLimit = Infinity;
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
    
    __karma__.loaded = function() {};
    
    System.config({
      packages: {
        'base/dist': {
            defaultExtension: false,
            format: 'cjs',
            map: Object.keys(window.__karma__.files).filter(onlyAppFiles).reduce(createPathRecords, {})
        }
      }
    });
    
    System.import('angular2/src/platform/browser/browser_adapter')
      .then(function(browser_adapter) { browser_adapter.BrowserDomAdapter.makeCurrent(); })
      .then(function() { return Promise.all(resolveTestFiles()); })
      .then(function() { __karma__.start(); }, function(error) { __karma__.error(error.stack || error); });
    
    function createPathRecords(pathsMapping, appPath) {
      var pathParts = appPath.split('/');
      var moduleName = './' + pathParts.slice(Math.max(pathParts.length - 2, 1)).join('/');
      moduleName = moduleName.replace(/\.js$/, '');
      pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath];
      return pathsMapping;
    }
    
    function onlyAppFiles(filePath) {
      return /\/base\/dist\/(?!.*\.spec\.js$).*\.js$/.test(filePath);
    }
    
    function onlySpecFiles(path) {
      return /\.spec\.js$/.test(path);
    }
    
    function resolveTestFiles() {
      return Object.keys(window.__karma__.files)
        .filter(onlySpecFiles)
        .map(function(moduleName) {
            return System.import(moduleName);
        });
    }
    

    以及 karma.conf.js 中的相应配置:

    module.exports = function(config) {
      config.set({
        basePath: '.',
        frameworks: ['jasmine'],
        files: [
          // paths loaded by Karma
          {pattern: 'node_modules/angular2/bundles/angular2-polyfills.js', included: true, watched: true},
          {pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: true},
          {pattern: 'node_modules/rxjs/bundles/Rx.js', included: true, watched: true},
          {pattern: 'node_modules/angular2/bundles/angular2.dev.js', included: true, watched: true},
          {pattern: 'node_modules/angular2/bundles/http.dev.js', included: true, watched: true},
          {pattern: 'node_modules/angular2/bundles/testing.dev.js', included: true, watched: true},
          {pattern: 'karma-test-shim.js', included: true, watched: true},
    
          // paths loaded via module imports
          {pattern: 'dist/**/*.js', included: false, watched: true},
    
          // paths to support debugging with source maps in dev tools
          {pattern: 'src/**/*.ts', included: false, watched: false},
          {pattern: 'dist/**/*.js.map', included: false, watched: false}
        ],
        (...)
      });
    };
    

    它认为这篇文章及其源代码可以帮助您:

  • 0

    非常感谢你 . 无法加载'tests / ** / * Spec.js'中的捆绑文件的说明非常有意义 .

    它现在正在运作 .

    为了使解释简单,我将karma-test-shim.js添加到文件部分,就是这样 .

    我稍后会更改文件部分样式 .

    module.exports = function(config) {
      config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
          'node_modules/systemjs/dist/system.src.js',
          'node_modules/angular2/bundles/angular2.dev.js',
          'karma-test-shim.js',
          'tests/**/*Spec.js'
        ],
        exclude: [
        ],
        preprocessors: {
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: ['Chrome', 'Firefox'],
        singleRun: false,
        concurrency: Infinity
      })
    }
    
  • 0

    karma.conf.js 文件中还需要另一件事

    basePath: '.',
    
    proxies: {
        // required for component assets fetched by Angular's compiler
        '/src/': '/base/src/'
    },
    

    需要,否则测试将不会执行

相关问题