无法对我的angular 4代码运行简单的karma测试
我试图对我的4个角组件做一个最小的测试,但我根本无法让它工作 我正在运行这个命令:无法对我的angular 4代码运行简单的karma测试,angular,karma-jasmine,karma-mocha,angular2-testing,karma-coverage,Angular,Karma Jasmine,Karma Mocha,Angular2 Testing,Karma Coverage,我试图对我的4个角组件做一个最小的测试,但我根本无法让它工作 我正在运行这个命令:karma start src/test/javascript/karma.conf.js 下面是输出:Error:这个测试模块使用组件AppComponent,它使用的是“templateUrl”或“styleurl”,但它们从未被编译过。测试前,请致电“TestBed.compileComponents”。 这是我的app.component.spec.ts文件: import { async, Compone
karma start src/test/javascript/karma.conf.js
下面是输出:Error:这个测试模块使用组件AppComponent,它使用的是“templateUrl”或“styleurl”,但它们从未被编译过。测试前,请致电“TestBed.compileComponents”。
这是我的app.component.spec.ts文件:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {AppComponent} from "../../../../../main/webapp/app/admin/app";
describe('AppComponent (minimal)', () => {
it('should create', () => {
TestBed.configureTestingModule({
declarations: [ AppComponent ]
})
.compileComponents();
const fixture = TestBed.createComponent(AppComponent);
const component = fixture.componentInstance;
expect(component).toBeDefined();
});
});
我只想测试我在app.component.ts文件中创建的一些函数,也许还想测试app.component.html中的一些HTTML
这是我的karma.conf.js文件:
const webpackConfig = require('../../../webpack/webpack.test.js');
const ChromiumRevision = require('puppeteer/package.json').puppeteer.chromium_revision;
const Downloader = require('puppeteer/utils/ChromiumDownloader');
const revisionInfo = Downloader.revisionInfo(Downloader.currentPlatform(), ChromiumRevision);
process.env.CHROMIUM_BIN = revisionInfo.executablePath;
const WATCH = process.argv.indexOf('--watch') > -1;
module.exports = (config) => {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'intl-shim'],
// plugins
plugins: [
require('karma-jasmine'),
require('karma-junit-reporter'),
require('karma-notify-reporter'),
require('karma-chrome-launcher'),
require('karma-remap-istanbul'),
require('karma-sonarqube-reporter'),
require('karma-webpack'),
require('karma-sourcemap-loader'),
require("karma-intl-shim")
],
// list of files / patterns to load in the browser
files: [
'spec/entry.ts'
],
// list of files to exclude
exclude: ['e2e/**'],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'spec/entry.ts': ['webpack', 'sourcemap']
},
webpack: webpackConfig(WATCH),
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'junit', 'progress', 'karma-remap-istanbul', 'notify', 'sonarqube'],
junitReporter: {
outputFile: '../../../../target/test-results/karma/TESTS-results.xml'
},
notifyReporter: {
reportEachFailure: true, // Default: false, will notify on every failed sepc
reportSuccess: true // Default: true, will notify when a suite was successful
},
remapIstanbulReporter: {
reports: { // eslint-disable-line
'lcovonly': 'target/test-results/coverage/report-lcov/lcov.info',
'html': 'target/test-results/coverage',
'text-summary': null
}
},
sonarqubeReporter: {
//basePath: 'src/app', // test files folder
basePath: './', // test files folder
filePattern: '**/*spec.ts', // test files glob pattern
encoding: 'utf-8', // test files encoding
outputFolder: 'target/test-results/karma', // report destination - target/test-results/karma
legacyMode: false, // report for Sonarqube < 6.2 (disabled)
reportName: 'karma-sonarqube-report.xml'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: WATCH,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromiumHeadlessNoSandbox'],
customLaunchers: {
ChromiumHeadlessNoSandbox: {
base: 'ChromiumHeadless',
flags: ['--no-sandbox']
}
},
// Ensure all browsers can run tests written in .ts files
mime: {
'text/x-typescript': ['ts','tsx']
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: !WATCH
});
};
通常在每次测试之前调用测试台,并初始化组件/夹具,而不是在每次测试中(通常)
description('AppComponent',()=>{
let组件:AppComponent;
let夹具:组件夹具;
beforeach(异步(()=>{
TestBed.configureTestingModule({
声明:[AppComponent]
})
.compileComponents();
}));
在每个之前(()=>{
fixture=TestBed.createComponent(AppComponent);
组件=fixture.componentInstance;
fixture.detectChanges();
});
它('应该创建',()=>{
expect(component.toBeTruthy();
});
});
从'@angular/core/testing'导入{ComponentFixture,TestBed,async};
从“../../../test.module”导入{UiTestModule};
从“../../../../../../main/webapp/app/shared”导入{AccountService,Principal}”;
从“../../../../../../main/webapp/app/dashboard/dashboard.service”导入{DashboardService}”;
从“../../../../../../main/webapp/app/admin/app”导入{AppService}”;
从“ng jhipster”导入{JhiEventManager,JhiParseLinks};
从“@angular/Router”导入{ActivatedRoute,Router}”;
从“../../../../../../../main/webapp/app/shared/alert/toaster alert.service”导入{toaster alertservice}”;
从“ng2 toastr”导入{ToastOptions,ToastsManager};
从“../../../../../../../main/webapp/app/admin/app”导入{AppComponent}”;
从“@angular/platform browser”导入{domsanizer}”;
从“rxjs”导入{observeable};
描述('AppComponent',()=>{
让comp:AppComponent;
let夹具:组件夹具;
//let服务:JhiHealthService;
常数fakeActivatedRoute={
快照:{数据:{},
}as激活路线;
beforeach(异步(()=>{
TestBed.configureTestingModule({
导入:[UiTestModule],
声明:[AppComponent],
供应商:[
应用服务,
JhiParseLinks,
校长,
{
提供:激活的路由,
使用价值:{
数据:{
//订阅:(fn:(值:数据)=>void)=>fn({
订阅:(fn:()=>void)=>fn({
//公司:公司,,
分页参数:{
页码:1
}
}),
},
参数:{
//订阅:(fn:(值:Params)=>void)=>fn({
订阅:(fn:()=>void)=>fn({
选项卡:0,
}),
},
快照:{
网址:[
{
路径:“foo”,
},
{
路径:'bar',
},
{
路径:“baz”,
},
],
},
},
},
{提供:路由器,useValue:null},
JhiEventManager,
消毒剂,
烤面包机警报服务,
会计服务,
祝酒嘉宾,
祝酒辞
]
}).overrideTemplate(AppComponent“”)
.compileComponents();
}));
在每个之前(()=>{
fixture=TestBed.createComponent(AppComponent);
comp=夹具。组件状态;
//服务=fixture.debugElement.injector.get(JhiHealthService);
});
描述('TODO3',()=>{
它('TODO4',()=>{
expect(comp.foo()).toEqual('bar');
});
});
});
我刚刚编辑了我的帖子(请参阅“编辑:当我使用此代码尝试时:”)。我正在使用您的代码,但仍然会收到相同的错误
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Error: Uncaught (in promise): Failed to load %3Cdiv%3E%0A%20%20%20%20%3Ch2%3E%0A%20%20%20%20%20%20%20%20%3Cspan%3EApplication%20Management%3C/span%3E%0A%20%20%20%20%20%20%20%20%3Cbutton%.....(lots and lots of "HTML" here)
at resolvePromise (http://localhost:9877webpack:///node_modules/zone.js/dist/zone.js:783:0 <- spec/entry.ts:93156:31)
at resolvePromise (http://localhost:9877webpack:///node_modules/zone.js/dist/zone.js:754:0 <- spec/entry.ts:93127:17)
at http://localhost:9877webpack:///node_modules/zone.js/dist/zone.js:831:0 <- spec/entry.ts:93204:17
at ZoneDelegate.invokeTask (http://localhost:9877webpack:///node_modules/zone.js/dist/zone.js:424:0 <- spec/entry.ts:92797:31)
...
Error: This test module uses the component AppComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test.
at TestBed._initIfNeeded (http://localhost:9877webpack:///node_modules/@angular/core/@angular/core/testing.es5.js:756:0 <- spec/entry.ts:36698:27)
at TestBed.createComponent (http://localhost:9877webpack:///node_modules/@angular/core/@angular/core/testing.es5.js:873:0 <- spec/entry.ts:36815:14)
at Function.TestBed.createComponent (http://localhost:9877webpack:///node_modules/@angular/core/@angular/core/testing.es5.js:652:0 <- spec/entry.ts:36594:29)
at UserContext.<anonymous> (http://localhost:9877webpack:///src/test/javascript/spec/app/admin/app.component.spec.ts:16:26 <- spec/entry.ts:80888:37)
...
Expected undefined to be truthy.
at UserContext.<anonymous> (http://localhost:9877webpack:///src/test/javascript/spec/app/admin/app.component.spec.ts:22:26 <- spec/entry.ts:80893:27)
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
declare let require: any;
const testsContext: any = require.context('./', true, /\.spec/);
testsContext.keys().forEach(testsContext);
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { UiTestModule } from '../../../test.module';
import {AccountService, Principal} from "../../../../../../main/webapp/app/shared";
import {DashboardService} from "../../../../../../main/webapp/app/dashboard/dashboard.service";
import {AppService} from "../../../../../../main/webapp/app/admin/app";
import {JhiEventManager, JhiParseLinks} from "ng-jhipster";
import {ActivatedRoute, Router} from "@angular/router";
import {ToasterAlertService} from "../../../../../../main/webapp/app/shared/alert/toaster-alert.service";
import {ToastOptions, ToastsManager} from "ng2-toastr";
import { AppComponent} from "../../../../../../main/webapp/app/admin/app";
import {DomSanitizer} from "@angular/platform-browser";
import {Observable} from "rxjs";
describe('AppComponent', () => {
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
// let service: JhiHealthService;
const fakeActivatedRoute = {
snapshot: { data: { } },
} as ActivatedRoute;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [UiTestModule],
declarations: [AppComponent],
providers: [
AppService,
JhiParseLinks,
Principal,
{
provide: ActivatedRoute,
useValue: {
data: {
// subscribe: (fn: (value: Data) => void) => fn({
subscribe: (fn: () => void) => fn({
// company: COMPANY,
pagingParams: {
page: 1
}
}),
},
params: {
// subscribe: (fn: (value: Params) => void) => fn({
subscribe: (fn: () => void) => fn({
tab: 0,
}),
},
snapshot: {
url: [
{
path: 'foo',
},
{
path: 'bar',
},
{
path: 'baz',
},
],
},
},
},
{ provide: Router, useValue: null },
JhiEventManager,
DomSanitizer,
ToasterAlertService,
AccountService,
ToastsManager,
ToastOptions
]
}).overrideTemplate(AppComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
// service = fixture.debugElement.injector.get(JhiHealthService);
});
describe('TODO3', () => {
it('TODO4', () => {
expect(comp.foo()).toEqual('bar');
});
});
});