2016-05-23 3 views
3

Я исправляю конфигурацию Karma для запуска тестов для версии Angular2 - rc 1. Я могу запустить тесты, но они терпят неудачу, если у меня есть переводная труба внутри html. (Конфигурационный я мог заставить его работать, я получил его от [здесь] [1])ng2-translate - Труба 'translate' не найдено

мой karma.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 

Один из моих тестов:

...

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

... описывают ('Вход Сообщения',() => {

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> 

...

Ошибка, возникающая при работе с кармой:

Невозможно найти трубу 'translate' ("class =" glyphicon glyphicon-info-sign msg-icon "> ] [innerHTML] =" msg.key | переводить "> "): LoginMessages @ 6: 47 Ошибка: Шаблон ошибки разбора: ...

отметить, что перевод труба работает нормально в фактическом приложении. Любые идеи были бы оценены!

+0

Никто не имеет подсказку о том, как настроить карму, чтобы увидеть эту трубу? Я чувствую, что я так близко ... –

ответ

1

Наконец-то я нашел ответ: это не проблема конфигурации Karma. Для трубы следует рассматривать в компоненте мне нужно, чтобы обеспечить его в тесте:

beforeEachProviders(() => [ 
    .... 
    provide(PLATFORM_PIPES, {useValue: TranslationPipe, multi: true}) 
    .... 
    ]) 
+0

Это не работает с модульным тестированием Angular 2.1.0. Он не распознает PLATFORM_PIPES. Любая помощь? – Protagonist

+0

Здесь я написал о том, как это сделать с ngx. (Угловая 4+) http://stackoverflow.com/a/43579026/356759 – nottinhill

Смежные вопросы