현재 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);
}
차이가 있는지는 확실하지 않지만 html의 경우 'included : false'여야합니다. –
성공적인 통화의 URL과 사양 러너에서 실패한 통화를 질문의 맨 아래에 추가했습니다. – devoncrazylegs
[quickstart] (https://github.com/angular/quickstart/blob/master/karma.conf.js)를 보면 카르마 설정 파일이있는 곳인 것처럼 보입니다. 프로젝트는 빠른 시작을 기반으로합니까? 나는 그것을 복제 할 수 있고 그 경우 문제를 재현하려고 노력할 수 있습니다. –