测试组件时出现 ng 测试问题
ng test problem while testing a component
我在 Angular 12 上测试组件时出现以下错误:
错误:模块 'DynamicTestModule' 导入了意外值 'ParamDecoratorFactory'。请添加 @NgModule 注释。
在 verifySemanticsOfNgModuleDef (http://localhost:9876/karma_webpack/vendor.js:85197:19)
在 http://localhost:9876/karma_webpack/vendor.js:85208:9
在 Array.forEach ()
在 verifySemanticsOfNgModuleDef (http://localhost:9876/karma_webpack/vendor.js:85206:60)
在 Function.get (http://localhost:9876/karma_webpack/vendor.js:85168:21)
在 R3TestBedCompiler.applyProviderOverridesToModule (http://localhost:9876/karma_webpack/vendor.js:92502:39)
在 R3TestBedCompiler.compileTestModule (http://localhost:9876/karma_webpack/vendor.js:92750:14)
在 R3TestBedCompiler.finalize (http://localhost:9876/karma_webpack/vendor.js:92356:14)
在 TestBedRender3.get testModuleRef [作为 testModuleRef] (http://localhost:9876/karma_webpack/vendor.js:93229:49)
在 TestBedRender3.inject (http://localhost:9876/karma_webpack/vendor.js:93152:29)
错误:预期 undefined 为真。
在
在用户上下文。 (http://localhost:9876/karma_webpack/main.js:1060:23)
在 ZoneDelegate.invoke (http://localhost:9876/karma_webpack/polyfills.js:382:26)
在 ProxyZoneSpec.onInvoke (http://localhost:9876/karma_webpack/vendor.js:120678:39)
spec.ts代码是这样的:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Inject } from '@angular/core';
import { MenuComponent } from './menu.component';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';
import { flyInOut, expand } from '../animations/app.animation';
describe('MenuComponent', () => {
let component: MenuComponent;
let fixture: ComponentFixture<MenuComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
Inject,
Dish,
DishService,
flyInOut,
expand
],
declarations: [ MenuComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MenuComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
component.ts代码是这样的:
import { Component, OnInit, Inject } from '@angular/core';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';
import { flyInOut, expand } from '../animations/app.animation';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss'],
// tslint:disable-next-line:use-host-property-decorator
host: {
'[@flyInOut]': 'true',
'style': 'display: block;'
},
animations: [
flyInOut(),
expand()
]
})
export class MenuComponent implements OnInit {
dishes!: Dish[];
errMess: string;
constructor(private dishService: DishService,
@Inject ('BaseURL') public baseURL) { }
ngOnInit(): void {
this.dishService.getDishes().subscribe((dishes => this.dishes = dishes), errMess => this.errMess = <any>errMess);
}
}
这是 dish.service.ts 代码:
import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { baseURL } from '../shared/baseurl';
import { map, catchError } from 'rxjs/operators';
import { ProcessHTTPMsgService } from './process-httpmsg.service';
@Injectable({
providedIn: 'root'
})
export class DishService {
constructor(private http: HttpClient, private processHTTPMsgService: ProcessHTTPMsgService) { }
getDishes(): Observable<Dish[]> {
return this.http.get<Dish[]>(baseURL + '/dishes').pipe(catchError(this.processHTTPMsgService.handleError));
}
getDish(id: string): Observable<Dish> {
return this.http.get<Dish>(baseURL + '/dishes/' + id).pipe(catchError(this.processHTTPMsgService.handleError));
}
getFeaturedDish(): Observable<Dish> {
return this.http.get<Dish[]>(baseURL + '/dishes?featured=true').pipe(map(dishes => dishes[0])).pipe(catchError(this.processHTTPMsgService.handleError));
}
getDishIds(): Observable<string[] | any> {
return this.getDishes().pipe(map(dishes => dishes.map(dish => dish.id))).pipe(catchError(error => error));
}
putDish(dish: Dish): Observable<Dish> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'})
};
return this.http.put<Dish>(baseURL + '/dishes/' + dish.id, dish, httpOptions).pipe(catchError(this.processHTTPMsgService.handleError));
}
}
感谢您的帮助
导入数组只需要模块(例如:FormsModule、翻译模块等)。您在这里将服务添加到导入列表中。
请将其添加到 spec.ts 文件中的提供商列表中。
describe('MenuComponent', () => {
let component: MenuComponent;
let fixture: ComponentFixture<MenuComponent>;
// mocking service to avoid actual HTTP calls
const mockDishService = {
getDishes: () => {
// sample JSON similar to api response
return {
id: '000',
name: 'nnnnn'
}
}
}
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [], // no module dependency so keeping it []
declarations: [ MenuComponent ],
providers: [
{ provide: DishService, useValue: mockDishService }
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MenuComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
我在 Angular 12 上测试组件时出现以下错误:
错误:模块 'DynamicTestModule' 导入了意外值 'ParamDecoratorFactory'。请添加 @NgModule 注释。 在 verifySemanticsOfNgModuleDef (http://localhost:9876/karma_webpack/vendor.js:85197:19) 在 http://localhost:9876/karma_webpack/vendor.js:85208:9 在 Array.forEach () 在 verifySemanticsOfNgModuleDef (http://localhost:9876/karma_webpack/vendor.js:85206:60) 在 Function.get (http://localhost:9876/karma_webpack/vendor.js:85168:21) 在 R3TestBedCompiler.applyProviderOverridesToModule (http://localhost:9876/karma_webpack/vendor.js:92502:39) 在 R3TestBedCompiler.compileTestModule (http://localhost:9876/karma_webpack/vendor.js:92750:14) 在 R3TestBedCompiler.finalize (http://localhost:9876/karma_webpack/vendor.js:92356:14) 在 TestBedRender3.get testModuleRef [作为 testModuleRef] (http://localhost:9876/karma_webpack/vendor.js:93229:49) 在 TestBedRender3.inject (http://localhost:9876/karma_webpack/vendor.js:93152:29)
错误:预期 undefined 为真。 在 在用户上下文。 (http://localhost:9876/karma_webpack/main.js:1060:23) 在 ZoneDelegate.invoke (http://localhost:9876/karma_webpack/polyfills.js:382:26) 在 ProxyZoneSpec.onInvoke (http://localhost:9876/karma_webpack/vendor.js:120678:39)
spec.ts代码是这样的:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Inject } from '@angular/core';
import { MenuComponent } from './menu.component';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';
import { flyInOut, expand } from '../animations/app.animation';
describe('MenuComponent', () => {
let component: MenuComponent;
let fixture: ComponentFixture<MenuComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
Inject,
Dish,
DishService,
flyInOut,
expand
],
declarations: [ MenuComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MenuComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
component.ts代码是这样的:
import { Component, OnInit, Inject } from '@angular/core';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';
import { flyInOut, expand } from '../animations/app.animation';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss'],
// tslint:disable-next-line:use-host-property-decorator
host: {
'[@flyInOut]': 'true',
'style': 'display: block;'
},
animations: [
flyInOut(),
expand()
]
})
export class MenuComponent implements OnInit {
dishes!: Dish[];
errMess: string;
constructor(private dishService: DishService,
@Inject ('BaseURL') public baseURL) { }
ngOnInit(): void {
this.dishService.getDishes().subscribe((dishes => this.dishes = dishes), errMess => this.errMess = <any>errMess);
}
}
这是 dish.service.ts 代码:
import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { baseURL } from '../shared/baseurl';
import { map, catchError } from 'rxjs/operators';
import { ProcessHTTPMsgService } from './process-httpmsg.service';
@Injectable({
providedIn: 'root'
})
export class DishService {
constructor(private http: HttpClient, private processHTTPMsgService: ProcessHTTPMsgService) { }
getDishes(): Observable<Dish[]> {
return this.http.get<Dish[]>(baseURL + '/dishes').pipe(catchError(this.processHTTPMsgService.handleError));
}
getDish(id: string): Observable<Dish> {
return this.http.get<Dish>(baseURL + '/dishes/' + id).pipe(catchError(this.processHTTPMsgService.handleError));
}
getFeaturedDish(): Observable<Dish> {
return this.http.get<Dish[]>(baseURL + '/dishes?featured=true').pipe(map(dishes => dishes[0])).pipe(catchError(this.processHTTPMsgService.handleError));
}
getDishIds(): Observable<string[] | any> {
return this.getDishes().pipe(map(dishes => dishes.map(dish => dish.id))).pipe(catchError(error => error));
}
putDish(dish: Dish): Observable<Dish> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'})
};
return this.http.put<Dish>(baseURL + '/dishes/' + dish.id, dish, httpOptions).pipe(catchError(this.processHTTPMsgService.handleError));
}
}
感谢您的帮助
导入数组只需要模块(例如:FormsModule、翻译模块等)。您在这里将服务添加到导入列表中。
请将其添加到 spec.ts 文件中的提供商列表中。
describe('MenuComponent', () => {
let component: MenuComponent;
let fixture: ComponentFixture<MenuComponent>;
// mocking service to avoid actual HTTP calls
const mockDishService = {
getDishes: () => {
// sample JSON similar to api response
return {
id: '000',
name: 'nnnnn'
}
}
}
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [], // no module dependency so keeping it []
declarations: [ MenuComponent ],
providers: [
{ provide: DishService, useValue: mockDishService }
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MenuComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});