在Angular单元测试中,如果需要测试多个视图组件,可以使用TestBed.createComponent创建组件实例,通过调用fixture.detectChanges()来更新组件的视图,并使用fixture.debugElement.queryAll()来查找子组件并进行测试。下面是一个示例:
import { Component, Input } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
@Component({
selector: 'app-child',
template: '{{title}}
',
})
class ChildComponent {
@Input() title: string;
}
@Component({
selector: 'app-parent',
template: `
`,
})
class ParentComponent {
titles = ['Title 1', 'Title 2', 'Title 3'];
}
describe('ParentComponent', () => {
let fixture: ComponentFixture;
let parent: ParentComponent;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ParentComponent);
parent = fixture.componentInstance;
fixture.detectChanges();
});
it('should create parent component with three child components', () => {
expect(parent).toBeTruthy();
expect(fixture.debugElement.queryAll(By.directive(ChildComponent)).length).toBe(3);
});
it('should display child component titles correctly', () => {
const childElements = fixture.debugElement.queryAll(By.directive(ChildComponent));
childElements.forEach((childElement, index) => {
const childComponent = childElement.componentInstance as ChildComponent;
const titleElement = childElement.query(By.css('h1')).nativeElement;
expect(titleElement.textContent).toEqual(parent.titles[index]);
});
});
});
该示例中,我们测试ParentComponent是否正确地渲染了三个ChildComponent,并测试每个ChildComponent的title是否正确显示。