示例代码:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture
beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ MyComponent ], providers: [ MyService ], imports: [ HttpClientModule, FormsModule ] }) .compileComponents(); }));
beforeEach(() => { fixture = TestBed.createComponent(MyComponent); component = fixture.componentInstance; element = fixture.debugElement;
fixture.detectChanges();
});
it('should render a list of items', async(() => { const items: Item[] = [ { id: 1, name: 'Item 1'}, { id: 2, name: 'Item 2'}, { id: 3, name: 'Item 3'} ];
spyOn(component.service, 'getItems').and.returnValue(of(items));
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.items.length).toBe(items.length);
expect(element.queryAll(By.css('.list-item')).length).toBe(items.length);
});
})); });