4

我正在修复我的 Karma 配置以运行 Angular2 - rc 1 版本的测试。我可以运行测试,但如果我在 html 中有一个翻译管道,它们就会失败。(我可以让它工作的配置我从 [这里] [1] 得到的)

我的业力.conf

   module.exports = function(config) {
  config.set({

    basePath: '',

    frameworks: ['jasmine'],

    files: [
      // Polyfills.
      'node_modules/es6-shim/es6-shim.js',

      'node_modules/reflect-metadata/Reflect.js',

      // System.js for module loading
      'node_modules/systemjs/dist/system-polyfills.js',
      'node_modules/systemjs/dist/system.src.js',

      // Zone.js dependencies
      'node_modules/zone.js/dist/zone.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 },
      { pattern: 'node_modules/ng2-translate/**/*.js', included: false, watched: false},

      {pattern: 'karma-test-shim.js', included: true, watched: true},

      // paths loaded via module imports
      // Angular itself
      // {pattern: 'node_modules/@angular/router-deprecated/index.js', included: false, watched: true},
      {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},
      // {pattern: 'node_modules/@angular2-material/**/*.js', included: false, watched: true},
      {pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false},

      // Our built application code
      {pattern: 'dist/**/*.js', included: false, watched: true},

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

      {pattern: 'dist/assets/images/**/*.jpg', watched: false, included: false, served: true},
      {pattern: 'dist/assets/images/**/*.png', watched: false, included: false, served: true},
      {pattern: 'dist/assets/i18n/**/*.json', watched: false, included: false, served: true},
      {pattern: 'dist/local_config.json', watched: false, included: false, served: true},
      // paths to support debugging with source maps in dev tools
      // {pattern: 'src/**/*.ts', included: false, watched: true},
      //{pattern: 'dist/**/*.js.map', included: false, watched: false}
    ],

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

    // list of files to exclude
    exclude: [
      'node_modules/@angular/**/*spec.js'
    ],

    // // preprocess matching files before serving them to the browser
    // // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'dist/**/!(*spec).js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter

    coverageReporter: {
        dir: 'coverage/',
        reporters: [
            { type: 'text-summary' },
            { type: 'json', subdir: '.', file: 'coverage-final.json' },
            { type: 'html' }
        ],
        instrumenterOptions: {
            istanbul: { noCompact: true }
        }
    },

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

我的 karma-test-shim.js

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

__karma__.loaded = function () {
};

var distPath = '/base/';
var appPath = distPath;

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

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

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

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

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

System.import('systemjs.config.test.js').then(function() {
  // Load and configure the TestComponentBuilder.
  return 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);


  [1]: http://stackoverflow.com/questions/37178267/angular2-rc1-karma-error-unable-to-find-angular-core-testing

我的一项测试:

...

import { TranslateService, TranslateLoader, TranslateStaticLoader} from 'ng2-translate';
import { TranslationService } from '../../services/localization/translation.service';

... describe('登录信息', () => {

    beforeEachProviders(() => [
        provide( CmsService, { useClass: MockCmsService }),
        provide(Config, { useClass: MockConfig }),
        ROUTER_PROVIDERS,
        HTTP_PROVIDERS,
        provide(Router, { useClass: MockRouter }),
        TranslateService,
        // provide(TranslateService, { useClass: MockTranslateService }),
        // provide(TranslationService, { useClass: MockTranslationService }),
        TranslationService,
        SessionService,
        provide(TranslateLoader, {
            useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
            deps: [Http]
        }),
        ModuleLoaderService,
        MyGlobals
    ]);

    beforeEach(() => {
        Config.params = {
            fleetVersionNumber: 'xyz'
        };
    });

    fit('should display messgages', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        return tcb.createAsync(LoginMessages).then((componentFixture) => {
            componentFixture.componentInstance.messages = MESSAGES;
            let element = componentFixture.nativeElement;
            componentFixture.detectChanges();
            expect(element.querySelectorAll('.msg-row').length).toBe(3);

            expect(element.querySelectorAll('.msg-row')[0].querySelector('span').innerText).toBe('Plain bla bla');

……

组件html:

...

<div style="margin:0 5px 0 25px"><span [innerHTML]="msg.key | translate "></span></div>

...

运行 Karma 时出现的错误:

找不到管道“翻译”(“class="glyphicon glyphicon-info-sign msg-icon"> ][innerHTML]="msg.key | translate "> "):LoginMessages@6:47 错误:模板解析错误:...

提到翻译管道在实际应用程序中工作正常。任何想法,将不胜感激!

4

1 回答 1

2

我终于找到了答案:这不是 Karma 配置问题。为了在组件中看到管道,我需要在测试中提供它:

  beforeEachProviders(() => [
     ....
     provide(PLATFORM_PIPES, {useValue: TranslationPipe, multi:  true})
     ....
  ])
于 2016-05-25T15:47:21.090 回答