【问题标题】:Issues getting Karma to work with SystemJS, Angular2 and Typescript让 Karma 与 SystemJS、Angular2 和 Typescript 一起工作的问题
【发布时间】:2016-05-11 15:26:41
【问题描述】:

我在让 Karma 与 SystemJS、Angular2 和 Typescript 一起工作时遇到问题。

这是我的 karma.conf.js:

'use strict';
module.exports = function (config) {
    config.set({

        // base path, that will be used to resolve files and exclude
        basePath: '.',

        // frameworks to use
        frameworks: ['systemjs', 'jasmine'],

        plugins: ['karma-systemjs', 'karma-jasmine', 'karma-phantomjs-launcher'],

        files: [
            'node_modules/reflect-metadata/Reflect.js',
            'app/**/*.spec.ts',
            //'jspm_packages/system-polyfills.js',
            'karma-test-shim.js'
        ],

        systemjs: {
            configFile: "systemjs.config.js",
            config: {
                //baseURL: ".",
                transpiler: "typescript",
                paths: {
                    "systemjs": "jspm_packages/system.js",
                    "system-polyfills": "jspm_packages/system-polyfills.js",
                    "typescript": "node_modules/typescript/lib/typescript.js"
                },
                packages: {
                    'app': {
                        defaultExtension: 'ts'
                    }
                }
            },
            includeFiles: [
                'node_modules/reflect-metadata/Reflect.js'
            ],
            serveFiles: [
                'app/**/*.ts',
                'main-bundle.js'
            ]
        },


        // proxied base paths
        proxies: {
            // required for component assets fetched by Angular's compiler
            "/app/": "/base/app/",
            "/jspm_packages/": "/base/jspm_packages/",
            "/node_modules/": "/base/node_modules/"
        },


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


        // 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: false,


        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['PhantomJS'],


        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 60000,


        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: true
    });
};

我的 karma-test-shim.js:

/*global jasmine, __karma__, window*/
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

__karma__.loaded = function () {
};


function isJsFile(path) {
    return path.slice(-3) == '.js';
}

function isSpecFile(path) {
    return path.slice(-8) == '.spec.js';
}

function isBuiltFile(path) {
    var builtPath = '/base/app/';
    return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath);
}

var allSpecFiles = Object.keys(window.__karma__.files)
    .filter(isSpecFile)
    .filter(isBuiltFile);

// Load our SystemJS configuration.
System.config({
    baseURL: '/base'
});

System.config(
    {
        map: {
            'rxjs': 'node_modules/rxjs',
            '@angular': 'node_modules/@angular',
            'app': 'app'
        },
        packages: {
            'app': {
                main: 'main.js',
                defaultExtension: 'js'
            },
            '@angular/core': {
                main: 'index.js',
                defaultExtension: 'js'
            },
            '@angular/compiler': {
                main: 'index.js',
                defaultExtension: 'js'
            },
            '@angular/common': {
                main: 'index.js',
                defaultExtension: 'js'
            },
            '@angular/platform-browser': {
                main: 'index.js',
                defaultExtension: 'js'
            },
            '@angular/platform-browser-dynamic': {
                main: 'index.js',
                defaultExtension: 'js'
            },
            'rxjs': {
                defaultExtension: 'js'
            }
        }
    });

Promise.all([
    System.import('@angular/core/testing'),
    System.import('@angular/platform-browser-dynamic/testing')
]).then(function (providers) {
    var testing = providers[0];
    var testingBrowser = providers[1];

    testing.setBaseTestProviders(testingBrowser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
        testingBrowser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);

}).then(function() {
    // Finally, load all spec files.
    // This will run the tests directly.
    return Promise.all(
        allSpecFiles.map(function (moduleName) {
            return System.import(moduleName);
        }));
}).then(__karma__.start, __karma__.error);

我的 systemjs.config.js:

(function (global) {

    // map tells the System loader where to look for things
    var map = {
        'app': 'app', // 'dist',
        'rxjs': 'node_modules/rxjs',
        'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
        '@angular': 'node_modules/@angular',
        'crypto': '@empty'// this fixed my last issue
    };

    // packages tells the System loader how to load when no filename and/or no extension
    var packages = {
        'app': {main: 'main.js', defaultExtension: 'js'},
        'rxjs': {defaultExtension: 'js'},
        'angular2-in-memory-web-api': {defaultExtension: 'js'}
    };

    var packageNames = [
        '@angular/common',
        '@angular/compiler',
        '@angular/core',
        '@angular/http',
        '@angular/platform-browser',
        '@angular/platform-browser-dynamic',
        '@angular/router',
        '@angular/upgrade'
    ];

    // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
    packageNames.forEach(function (pkgName) {
        packages[pkgName] = {main: 'index.js', defaultExtension: 'js'};
    });

    var config = {
        map: map,
        packages: packages
    };

    // filterSystemConfig - index.html's chance to modify config before we register it.
    if (global.filterSystemConfig) {
        global.filterSystemConfig(config);
    }

    System.config(config);

})(this);

当我使用 karma start karma.conf.js 运行测试时,我的测试位于主要的 ts 文件旁边。

我收到此错误:

11 05 2016 17:02:24.306:DEBUG [web-server]: serving (cached): /Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/node_modules/typescript/lib/typescript.js
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  Error: eval code
    eval@[native code]
    F@/Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/jspm_packages/system-polyfills.js:4:12217
    H@/Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/jspm_packages/system-polyfills.js:4:11846
    when@/Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/jspm_packages/system-polyfills.js:4:15520
    run@/Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/jspm_packages/system-polyfills.js:4:14559
    _drain@/Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/jspm_packages/system-polyfills.js:4:3250
    drain@/Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/jspm_packages/system-polyfills.js:4:1667
    Evaluating /Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/karma-test-shim.js
    Error loading /Users/julien/Documents/projects/bignibou/bignibou-site/bignibou-client/karma-test-shim.js


11 05 2016 17:02:24.316:DEBUG [karma]: Run complete, exiting.
11 05 2016 17:02:24.316:DEBUG [launcher]: Disconnecting all browsers
11 05 2016 17:02:24.324:DEBUG [launcher]: Process PhantomJS exited with code 0
11 05 2016 17:02:24.324:DEBUG [temp-dir]: Cleaning temp dir /var/folders/1p/pcqq7s0x58l_s7ds52gxt_fw0000gp/T/karma-62098834
11 05 2016 17:02:24.329:DEBUG [launcher]: Finished all browsers
npm ERR! Test failed.  See above for more details.

有人可以帮忙吗?

【问题讨论】:

  • 你检查过本教程和示例项目吗? jaxenter.com/…
  • 谢谢托马斯。我查看了建议的示例项目,但它不是基于 Karma-SystemJS。您是否亲自设法获得了 Karma/SystemJs/Typescript 项目?
  • 该示例使用 System.js,但基于较旧的 Angular 2 版本。我假设您在 karma-shim 中配置了错误的 System.js。你有一个“基础”目录吗?
  • @balteo 我建议你安装angular-cli 并在那里生成一个项目,生成项目中的业力设置使用相同的工具链。 (TypeScript、Karma、SystemJS)
  • 感谢大家的建议。我宁愿通过了解问题的根源来确定我的配置有什么问题。

标签: typescript angular karma-runner karma-jasmine systemjs


【解决方案1】:

过去几天我一直在研究所有不同的 A2 种子/cli,其中 90% 都在使用旧的 A2 代码,我发现很难将它们解释为最新的 A2 代码。

我最终找到了这个。 https://github.com/juliemr/ng2-test-seed

这让我的业力测试使用 systemjs 运行。这是一个非常好的非常简单的项目,它可以获得基础知识,并且不会强加给你额外的垃圾。

您需要更改一些文件 url 以匹配您正在使用的任何内容。按照我的指导,我能够使用 typescript 和 systemjs 运行单元测试。

【讨论】:

  • 在使用 phantomjs 运行时包含 system-polyfill 为我节省了时间
  • 实际上有了这个我也遇到了同样的问题,就像没有它一样,我克隆了她的仓库并运行构建然后测试,0 个测试中的 0 个 - 业力不会匹配任何文件路径
  • @longbow 确保您的路径中没有符号链接,或者正确遵循符号链接
【解决方案2】:

我可以看到你所做的一些问题。

首先我认为你配置了两次SystemJS:

  • 曾在test-shim-karma.js 文件中
  • karma.conf.js 中一次通过 SystemJS 业力插件。

那么您无需配置将在您的规范文件中使用的源模块:

packages['base/app'] = {
  defaultExtension: 'js',
  format: 'cjs',
  map: Object.keys(window.__karma__.files).filter(onlyAppFiles).reduce(createPathRecords, {})
};

您多次调用System.config 方法。

我还会在您的karma.conf.js 文件的files 部分添加一些条目:

files: [
  // Paths loaded by Karma
  {pattern: 'node_modules/es6-shim/es6-shim.min.js', included: true, watched: true},
  {pattern: 'node_modules/reflect-metadata/Reflect.js', included: true, watched: true},
  {pattern: 'node_modules/zone.js/dist/zone.js', included: true, watched: true},
  {pattern: 'node_modules/zone.js/dist/async-test.js', included: true, watched: true},
  {pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: true, watched: true},
  {pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: true},
  {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false},
  {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},
  {pattern: 'karma-test-shim.js', included: true, watched: true},

  // Paths loaded via module imports
  {pattern: 'app/**/*.js', included: false, watched: true},

  // Paths to support debugging with source maps in dev tools
  {pattern: 'app/**/*.ts', included: false, watched: true},
  {pattern: 'app/**/*.js.map', included: false, watched: false}
],

您可以查看这个项目,了解使用 Angular2 RC1 和 TypeScript 的 Karma 工作配置:

【讨论】:

  • 谢谢蒂埃里。我已经调整了我的配置以匹配您的配置。我在 mac osX 上收到一个错误,有几个人使用 karma 0.13.22 看到这里:github.com/karma-runner/karma/issues/…
  • 大多数情况下,此错误对应于您的 files 配置中的错误路径。例如:{pattern: 'node_modules/zone.js/dist/zonejs.js', included: true, watched: true},instanceof {pattern: 'node_modules/zone.js/dist/zone.js', included: true, watched: true},。在旧版本的 Karma 中,消息不是很明确 ;-) 它已在最新版本中修复...
  • 我使用的是最新版本的 Karma
  • 你有什么提示可以得到更明确的错误信息吗?您所说的“最新版本”指的是哪个版本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 2016-10-09
  • 1970-01-01
  • 2016-09-08
  • 2016-05-11
  • 1970-01-01
  • 2016-07-22
相关资源
最近更新 更多