4

Angular2 - rc 1 バージョンのテストを実行するように Karma 構成を修正しています。テストを実行できますが、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
  })
}

私のカルマ-テスト-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

私のテストの1つ:

...

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 の実行時に表示されるエラー:

パイプ 'translate' が見つかりませんでした ("class="glyphicon glyphicon-info-sign msg-icon"> ][innerHTML]="msg.key | translate "> "): LoginMessages@6:47 エラー: テンプレート解析エラー: ...

翻訳パイプが実際のアプリ内で正常に機能することを言及します。どんなアイデアでも大歓迎です!

4

1 に答える 1

2

私は最終的に答えを見つけました:それはカルマの設定の問題ではありませんでした. コンポーネント内にパイプが表示されるようにするには、テストでパイプを提供する必要がありました。

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