使用Angular 2进行业力设置

时间:2016-11-03 18:17:02

标签: angular unit-testing karma-runner

我正在使用Angular 2 Web应用程序设置业力。但是,我一直试图让业力加载我的应用程序文件和我的.spec文件。我已经做了好几天了,但仍然没有运气。

我从github上的角度快速启动应用程序中获取了代码,并对其进行了修改以适应我当前的设置。

到目前为止,我只能得到报告404s的业力。我不知道从这里可以去哪里或者我可以问什么问题因为我已经尝试了所有我能想到的东西。另外,关于如何使用Angular 2和System j正确配置Karma的信息很少,因此非常感谢任何帮助或好的教程。

我的应用程序的当前设置

root:
  systemjs.config.js
  app -> contains my ts files and transpiled files
  node_modules
  test
    |_ karma.conf.js
    |_ karma-test-shim.js
    |_ protractor.config.js
    |_ unit
          |_ all spec files
    |_ e2e
          |_ all protractor test files

这是我目前的业力配置文件

Karma.conf.js:

module.exports = function(config) {
  var app = './app/'; // app source TS files
  var testBase = 'target/build/unit/'; // transpiled test JS and map files
  var testSrc = 'test/unit/'; // test source TS files
  var node_modules = 'node_modules/';

  config.set({
    basePath: '../',
    frameworks: ['jasmine'],
    plugins: [
      require('karma-jasmine'),
      require('karma-junit-reporter'),
      require('karma-chrome-launcher'),
      require('karma-phantomjs-launcher'),
      require('karma-ie-launcher'),
      require('karma-firefox-launcher')
    ],
    files: [
      // System.js for module loading
      node_modules + 'systemjs/dist/system.src.js',

      // Polyfills
      node_modules + 'core-js/client/shim.js',
      node_modules + 'reflect-metadata/Reflect.js',

      // zone.js
      node_modules + 'zone.js/dist/zone.js',
      node_modules + 'zone.js/dist/long-stack-trace-zone.js',
      node_modules + 'zone.js/dist/proxy.js',
      node_modules + 'zone.js/dist/sync-test.js',
      node_modules + 'zone.js/dist/jasmine-patch.js',
      node_modules + 'zone.js/dist/async-test.js',
      node_modules + 'zone.js/dist/fake-async-test.js',
      node_modules + 'requirejs/requirejs.js',

      // RxJs
      {pattern: node_modules + 'rxjs/**/*.js', included: false, watched: false},
      {pattern: node_modules + 'rxjs/**/*.js.map', included: false, watched: false},

      // Paths loaded via module imports: Angular itself
      {pattern: node_modules + '@angular/**/*.js', included: false, watched: false},
      {pattern: node_modules + '@angular/**/*.js.map', included: false, watched: false},
      {pattern: 'systemjs.config.js', included: false, watched: false},
      'test/karma-test-shim.js',

      // transpiled application files
      {pattern: app + '**/*.js', included: false, watched: true},

      //transpiled spec files
      {pattern: testBase + '**/*.spec.js', included: false, watched: true},
      {pattern: testBase + '**/*.js.map', included: false, watched: false},

      // Asset (HTML & CSS) paths loaded via Angular's component compiler
      // (these paths need to be rewritten, see proxies section)
      {pattern: app + '**/*.html', included: false, watched: true},
      {pattern: app + '**/*.css', included: false, watched: true},

      // Paths for debugging with source maps in dev tools
      {pattern: app + '**/*.ts', included: false, watched: false},
      {pattern: app + '**/*.js.map', included: false, watched: false},
      {pattern: testSrc + '**/*.spec.ts', included: false, watched: false}
    ],

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

    exclude: [],
    preprocessors: {},
    colors: true,
  });
}

业力试验垫片,JS

// #docregion
// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing.

// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
// Error.stackTraceLimit = Infinity; //

jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

var builtPath = '/base/app/';

__karma__.loaded = function () { };

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

function isSpecFile(path) {
  return /\.Spec\.(.*\.)?js$/.test(path);
}

function isBuiltFile(path) {
  return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath);
}

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

System.config({
  baseURL: '/base',

  // Map the angular testing umd bundles
  map: {
    '@angular/core/testing': '../node_modules/:@angular/core/bundles/core-testing.umd.js',
    '@angular/common/testing': '../node_modules/:@angular/common/bundles/common-testing.umd.js',
    '@angular/compiler/testing': '../node_modules/:@angular/compiler/bundles/compiler-testing.umd.js',
    '@angular/platform-browser/testing': '../node_modules/:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
    '@angular/platform-browser-dynamic/testing': '../node_modules/:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
    '@angular/http/testing': '../node_modules/:@angular/http/bundles/http-testing.umd.js',
    '@angular/router/testing': '../node_modules/:@angular/router/bundles/router-testing.umd.js',
    '@angular/forms/testing': '../node_modules/:@angular/forms/bundles/forms-testing.umd.js',
  },
});

System.import('../systemjs.config.js')
  .then(initTestBed)
  .then(initTesting);

function initTestBed(){
  return Promise.all([
    System.import('@angular/core/testing'),
    System.import('@angular/platform-browser-dynamic/testing')
  ])

  .then(function (providers) {
    var coreTesting    = providers[0];
    var browserTesting = providers[1];

    coreTesting.TestBed.initTestEnvironment(
      browserTesting.BrowserDynamicTestingModule,
      browserTesting.platformBrowserDynamicTesting());
  })
}

// Import all spec files and start karma
function initTesting () {
  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',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs',
    'primeng':                    'node_modules/primeng',
    'ic-components':              'node_modules/ic-components'
  };
  // 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': { main: 'index.js', defaultExtension: 'js' },
    'primeng':                    { defaultExtension: 'js' },
    'ic-components':              { main: 'index.js', defaultExtension: 'js' }
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

我得到的错误

Chrome 54.0.2840 (Windows 7 0.0.0) ERROR: 'Unhandled Promise rejection:', '(SystemJS) XHR error (404 Not Found) loading http://localhost:9090/systemjs.config.js
[INFO]  Error: XHR error (404 Not Found) loading http://localhost:9090/systemjs.config.js
[INFO]  Error loading http://localhost:9090/systemjs.config.js', '; Zone:', '<root>', '; Task:', 'Promise.then', '; Value:', Error{originalErr: Error{}}, '(SystemJS) XHR error (404 Not Found) loading http://localhost:9090/systemjs.config.js
[INFO]  Error: XHR error (404 Not Found) loading http://localhost:9090/systemjs.config.js
[INFO]  Error loading http://localhost:9090/systemjs.config.js'
[INFO] 
[INFO] Chrome 54.0.2840 (Windows 7 0.0.0) ERROR: Error{rejection: Error{originalErr: Error{}}, promise: ZoneAwarePromise{__zone_symbol__state: 0, __zone_symbol__value: Error{originalErr: ...}}, zone: Zone{_properties: Object{}, _parent: null, _name: '<root>', _zoneDelegate: ZoneDelegate{_taskCounts: ..., zone: ..., _parentDelegate: ..., _forkZS: ..., _forkDlgt: ..., _interceptZS: ..., _interceptDlgt: ..., _invokeZS: ..., _invokeDlgt: ..., _handleErrorZS: ..., _handleErrorDlgt: ..., _scheduleTaskZS: ..., _scheduleTaskDlgt: ..., _invokeTaskZS: ..., _invokeTaskDlgt: ..., _cancelTaskZS: ..., _cancelTaskDlgt: ..., _hasTaskZS: ..., _hasTaskDlgt: ...}}, task: ZoneTask{runCount: 1, type: 'microTask', zone: Zone{_properties: ..., _parent: ..., _name: ..., _zoneDelegate: ...}, source: 'Promise.then', data: undefined, scheduleFn: undefined, cancelFn: null, callback: function () { ... }, invoke: function () { ... }}}
[INFO] 
[INFO] [33m03 11 2016 14:14:45.699:WARN [Firefox 49.0.0 (Windows 7 0.0.0)]: [39mDisconnected (1 times), because no message in 10000 ms.
[INFO] Firefox 49.0.0 (Windows 7 0.0.0) ERROR
[INFO]   Disconnected, because no message in 10000 ms.
[INFO] 
[INFO] 
[INFO] [36m03 11 2016 14:14:45.738:DEBUG [launcher]: [39mProcess Firefox exited with code 0
[INFO] [33m03 11 2016 14:14:45.885:WARN [Chrome 54.0.2840 (Windows 7 0.0.0)]: [39mDisconnected (1 times), because no message in 10000 ms.
[INFO] Chrome 54.0.2840 (Windows 7 0.0.0) ERROR
[INFO]   Disconnected, because no message in 10000 ms.

我尝试过使用baseUrl,basePath,并在karma文件数组下将included更改为true。但是,所有不同的修改都导致了不同的神秘错误。

感谢您的帮助。

0 个答案:

没有答案