2016-12-07 2 views
1

현재 Angular2 응용 프로그램에 대한 몇 가지 테스트를 작성하려고하는데 템플릿 대신 Angular2 구성 요소의 templateUrl 속성 (HTML 파일에 연결)을 사용하면 테스트가 실행되지 않습니다. .html 파일이로드되지 않았으므로 테스트 내의 비동기 호출이 시간 초과됩니다. 구성 요소 파일 내에 템플릿 코드를 배치하면 올바르게 작동합니다. 내 브라우저에서 .html 시간 초과 요청을 볼 수도 있으므로 .html 파일이 발견되지 않는 문제가 발생합니다.Angular2 구성 요소 테스트. Karma not templateUrl

나는 내 karma.conf 파일을 살펴 봤는데 모든 것이 순서대로되어있는 것 같습니다. 또한 카르마가 karma.conf 파일에서 실행 중일 때 .html 중에서 파일을 포함하는 '사실'이 줄을 설정 한 :

module.exports = function(config) { 

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

    // Testing helpers (optional) are conventionally in a folder called `testing` 
    var testingBase = 'testing/'; // transpiled test JS and map files 
    var testingSrcBase = 'testing/'; // test source TS files 

    config.set({ 
     basePath: '', 
     frameworks: ['jasmine'], 

     plugins: [ 
      require('karma-jasmine'), 
      require('karma-chrome-launcher'), 
      require('karma-jasmine-html-reporter') 
     ], 

     client: { 
      builtPaths: [appSrcBase, testingBase], // add more spec base paths as needed 
      clearContext: false // leave Jasmine Spec Runner output visible in browser 
     }, 

     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', // optionally extend SystemJS mapping e.g., with barrels 

      // transpiled application & spec code paths loaded via module imports 
      { pattern: appBase + '**/*.js', included: false, watched: true }, 
      { pattern: testingBase + '**/*.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: true, 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: testingSrcBase + '**/*.ts', included: false, watched: false }, 
      { pattern: testingBase + '**/*.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: {}, 
     reporters: ['progress', 'kjhtml'], 

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

I : 여기

{ pattern: appBase + '**/*.html', included: true, watched: true }, 

내 전체 karma.conf 파일입니다 이 .html 파일이로드되지 않는 이유를 알 수 없으므로이 문제가 발생하는 이유를 누구나 볼 수 있습니까? 템플릿 코드는 각 구성 요소에 포함하기를 원하지 않습니다. 그 중 일부는 매우 커서 파일 구조가 이미 별도의 뷰 파일 기능을 보완하고 있기 때문입니다.

(주석 작동 코드) 구성 요소 :

import { Component } from "@angular/core"; 

@Component({ 
    selector: 'categories-component', 
    templateUrl: '/app/views/catalog/categories/categories-dashboard.html', 
    //template: '<h1>{{ title }}</h1>', 
    moduleId: module.id 
}) 

export class CategoriesComponent { 
    public title:String = 'Categories'; 
} 

테스트 모듈 : 나는 또한 카르마 시작할 때 카르마 러너에서이 오류가

import {TestBed, ComponentFixture, ComponentFixtureAutoDetect, async} from "@angular/core/testing"; 
import { By} from "@angular/platform-browser"; 
import { CategoriesComponent } from "../../../../components/catalog/categories/CategoriesComponent"; 
import { DebugElement } from "@angular/core"; 

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

describe('Component: CategoriesComponent',() => { 

    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      declarations: [ CategoriesComponent ], 
      providers: [ 
       { provide: ComponentFixtureAutoDetect, useValue: true } 
      ] 
     }); 
    }); 

    it('should display original title', (done) => { 
     TestBed.compileComponents() 
      .then(() => { 
       done(); 
       fixture = TestBed.createComponent(CategoriesComponent); 

       comp = fixture.componentInstance; // CategoriesComponent test instance 

       // query for the title <h1> by CSS element selector 
       de = fixture.debugElement.query(By.css('h1')); 
       el = de.nativeElement; 

       expect(el.textContent).toContain(comp.title); 
       done(); 
      }); 
    }); 
}); 

:

07 12 2016 14:17:15.658:WARN [proxy]: failed to proxy app/views/catalog/categories/categories-dashboard.html (socket hang up) 

내 대답에 명확한 설명을 추가하기 위해이 URL을 추가하고 있습니다. 나는 응용 프로그램에 액세스 할 때 템플릿의 성공적인 XHR 요청은 다음과 같습니다

http://product-admin.dev/app/views/catalog/categories/categories-dashboard.html 

와 (과 실패) 테스트 러너에서 템플릿을 얻기 위해 호출되는 URL은 다음과 같습니다

http://localhost:9879/app/views/catalog/categories/categories-dashboard.html 

카르마 테스트 심 파일 :

// /*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; 

// builtPaths: root paths for output ("built") files 
// get from karma.config.js, then prefix with '/base/' (default is 'app/') 
var builtPaths = (__karma__.config.builtPaths || ['app/']) 
    .map(function(p) { return '/base/'+p;}); 

__karma__.loaded = function() { }; 

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

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

// Is a "built" file if is JavaScript file in one of the "built" folders 
function isBuiltFile(path) { 
    return isJsFile(path) && 
     builtPaths.reduce(function(keep, bp) { 
      return keep || (path.substr(0, bp.length) === bp); 
     }, false); 
} 

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); 
} 
+0

차이가 있는지는 확실하지 않지만 html의 경우 'included : false'여야합니다. –

+0

성공적인 통화의 URL과 사양 러너에서 실패한 통화를 질문의 맨 아래에 추가했습니다. – devoncrazylegs

+0

[quickstart] (https://github.com/angular/quickstart/blob/master/karma.conf.js)를 보면 카르마 설정 파일이있는 곳인 것처럼 보입니다. 프로젝트는 빠른 시작을 기반으로합니까? 나는 그것을 복제 할 수 있고 그 경우 문제를 재현하려고 노력할 수 있습니다. –

답변

3

나는이 일을 할 수 있었지만 어떻게 이해할 수는 없다. 나는 다음에 appAssets 변수를 변경 :

var appAssets = '/base/app/'; // component assets fetched by Angular's compiler 

나는 이것이 내가 내 파일 구조에서 볼 수없는 것처럼 '기본'파일이 존재하는 경우 확실하지 않다으로 일했다 방법을 이해하지 않습니다. 그래도 누군가가 위대한 것이라고 더 이상의 설명을하고 싶다면 그렇게했습니다.

+0

SystemJS 설정에서 발생할 수 있다고 생각합니다.카르마 테스트 심을 보면 baseURL이'base'로 설정되어 있다고 생각합니다. 나는 그것이 완전히 확실하지는 않지만 그것이 그것과 관련이있을 것이라고 생각합니다. 그래도 소리 같아. –

+0

당신이 맞는 것 같습니다. 나는 karma-test-shim 파일도 추가했다. 그래서 SystemJS 구성의 baseURL 속성은 모든 요청에 ​​모든 값을 추가합니다. – devoncrazylegs

+0

나는 완전히 확신하지 못한다. –

관련 문제