1

我的 Karma 无法加载 angular 2 组件。删除此错误:

[web-server] :404 : /base/src/client/app/container/container.component

我用 Angular 2 测试教程做所有事情(我只修改了业力中的路径)所以问题必须在路径中。但我不知道如何解决它。

我自己的路:

src
|    |client
|    |   |container
|    |   |   |container.component.ts
|    |   |   |container.component.spec.ts
|karma.conf.js
|karma-test-shim.js

容器.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user/user.service';
import { User } from '../user/user';
//import { FacebookLogin } from '../facebook/fb-login';
//import { Facebook } from '../facebook/facebook';

@Component({
    selector: 'app-container',
    //templateUrl: '../../views/content.html',
    template: `Hello World`,
    providers: [UserService]
})
export class ContainerComponent implements OnInit{
     user: User;
    // constructor(private userService: UserService) {
    //     this.loadUser();
    //     if(typeof FB == 'undefined') {console.log("NULL");}
    // }


    // loadUser() {
    //     this.userService.getMockUser().then(userData => 
    //     {
    //         this.user = userData
    //         console.log("User data: " + userData.email);
    //     });
    // }

    ngOnInit(){

    }


}

container.component.spec.ts

import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { ContainerComponent } from './container.component';

let comp: ContainerComponent;
let fixture: ComponentFixture<ContainerComponent>;
let de: DebugElement;
let el: HTMLElement;

describe('Container Component', () => {
    // beforeEach( async(() => {
    //     TestBed.configureTestingModule({
    //         declarations: [ContainerComponent],
    //     }).compileComponents();

    //     fixture = TestBed.createComponent(ContainerComponent);
    //     comp = fixture.componentInstance;

    // }));

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ContainerComponent], // declare the test component
        });



    });

});

业力.conf.js

    // #docregion
    module.exports = function(config) {

      var appBase    = 'src/client/app/';       // transpiled app JS and map files
      var appSrcBase = 'src/client/app/';       // app source TS files
      var appAssets  = '/base/app/'; // component assets fetched by Angular's compiler

      var testBase    = 'testing/';       // transpiled test JS and map files
      var testSrcBase = 'testing/';       // test source TS files

      config.set({
        basePath: '',
        frameworks: ['jasmine'],
        plugins: [
          require('karma-jasmine'),
          require('karma-chrome-launcher'),
          require('karma-jasmine-html-reporter'), // click "Debug" in browser to see it
          require('karma-htmlfile-reporter') // crashing w/ strange socket error
        ],

        customLaunchers: {
          // From the CLI. Not used here but interesting
          // chrome setup for travis CI using chromium
          Chrome_travis_ci: {
            base: 'Chrome',
            flags: ['--no-sandbox']
          }
        },
        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',

          // 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},
          {pattern: 'systemjs.config.extras.js', included: false, watched: false},
          'karma-test-shim.js',

          // transpiled application & spec code paths loaded via module imports
          {pattern: appBase + '**/*.js', included: false, watched: true},
          {pattern: testBase + '**/*.js', included: false, watched: true},


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

          // Paths for debugging with source maps in dev tools
          {pattern: appSrcBase + '**/*.ts', included: false, watched: false},
          {pattern: appBase + '**/*.js.map', included: false, watched: false},
          {pattern: testSrcBase + '**/*.ts', included: false, watched: false},
          {pattern: testBase + '**/*.js.map', included: false, watched: false}
        ],

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

        exclude: [],
        preprocessors: {},
        // disabled HtmlReporter; suddenly crashing w/ strange socket error
        reporters: ['progress', 'kjhtml'],//'html'],

        // HtmlReporter configuration
        htmlReporter: {
          // Open this file to see results in browser
          outputFile: '_test-output/tests.html',

          // Optional
          pageTitle: 'Unit Tests',
          subPageTitle: __dirname
        },

        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        singleRun: false
      })
    }


karma-test-shim.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/src/client/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',
  // Extend usual application package list with test folder
  packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } },

  // Assume npm: is set in `paths` in systemjs.config
  // Map the angular testing umd bundles
  map: {
    '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
    '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
    '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
    '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
    '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
    '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
    '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
    '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js',
  },
});

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

/** Optional SystemJS configuration extras. Keep going w/o it */
function importSystemJsExtras(){
  return System.import('systemjs.config.extras.js')
  .catch(function(reason) {
    console.log(
      'Warning: System.import could not load the optional "systemjs.config.extras.js". Did you omit it by accident? Continuing without it.'
    );
    console.log(reason);
  });
}

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);
}
4

1 回答 1

1

我最近遇到了同样的问题,我得出的结论是 SystemJS 负责默认扩展(应该是“js”)。确保您的 ng2 应用程序文件夹与您的 systemjs.config 文件正确连接。

(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // app is within the app folder
      app: 'app', <<<<<<<------ HERE

      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',

      // other libraries
      'rxjs':                       'npm:rxjs',
      'angular-in-memory-web-api':  'npm:angular-in-memory-web-api'
    },
    packages: {
      app: { <<<<<<<------ HERE
        main: './main.js',
        defaultExtension: 'js' <<<<<<----- Important!!
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular-in-memory-web-api': {
        main: 'server/server.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);

如果这是正确的并且仍然存在问题,则可能是您的业力 Web 服务器和节点服务器为您的客户端文件提供服务的方式不一致。您可以在 karma.conf 文件中添加代理...

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

希望这可以帮助!C:

于 2016-10-07T05:19:05.203 回答