我有两个子组件 PatternsList 和 PatternsDetails 的模式页面 我已经使用路由并使用 params 单击 PattersList 页面以进入详细信息页面。我想进行单元测试并收到错误:无法读取未定义的属性“queryAll” 我的代码: 图案
<div class="container-fluid">
<h4 >Please select any pattern to get more information about it!</h4>
<div class="row" >
<div class="col-xs-4" *ngFor='let pattern of patterns; let i =index;' >
<a [routerLink] = "[i]">
**<img [src]="pattern.imagePath" alt="{{ pattern.name }}" id='detect' class="img-responsive" style="max-height: 200px;" >**
<div class="caption">{{ pattern.name | titlecase}}</div>
<p class="img_description">{{pattern.description}}</p>
</a>
</div>
</div>
</div>
patternDetail.ts 有:
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.id = +params['id'];
this.pattern = this.patternService.getPattern(this.id);
});
}
我正在尝试对 detailComponent 进行单元测试,如下所示:
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
PatternService,
{
provide: ActivatedRoute,
useValue: {
params: of({ id: 3 }),
},
},
],
imports: [
HttpClientTestingModule,
RouterTestingModule.withRoutes(appRoutes),
],
declarations: [PatternDetailComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(PatternDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
// it('should create', () => {
// expect(component).toBeTruthy();
// });
it(
'should navigate to a particular pattern when clikced on it on the list of patterns ',
fakeAsync(() => {
let fixture = TestBed.createComponent(PatternsListComponent);
let component = fixture.debugElement.componentInstance;
let router = TestBed.inject(Router);
let location = TestBed.inject(Location);
router.initialNavigation();
tick();
router.navigate(['patterns']);
tick();
expect(location.path()).toBe('/patterns');
fixture.detectChanges();
let divEle = component.nativeElement.queryAll(By.css('#detect'));
divEle[3].click();
tick();
fixture.detectChanges();
let detailFixture= TestBed.createComponent(PatternDetailComponent);
let detailComp= detailFixture.debugElement.componentInstance;
detailFixture.detectChanges();
tick();
expect(detailComp.pattern.id).toBe(3);
})
);
});
路径是这样定义的:
{ path: 'patterns', component:PatternsComponent, children:[
{ path: '',component:PatternsListComponent },
{ path: ':id',component:PatternDetailComponent}
]},
我是 Angular 和单元测试的新手,我试图点击 img 并进行导航,但出现错误:无法读取未定义的属性“queryAll”。我也尝试使用 querySelectorAll('#detect') 也给出了同样的错误。可能是什么原因?