如何测试渲染了多少个组件

How to test how many components are rendered

我尝试测试一个组件的渲染次数是否与我在 Angular 中预期的一样多。例如应用程序接收器

我正在测试具有以下内容的组件 html:

<div class="wichtel-form-container">
  <form class="wichteln-group-form" *ngIf="router.url == '/dostuff'" 
     #startWichtelForm="ngForm">
     <div class="form-group-container">
        <app-sender class=".sender" [sender]="sender"></app-sender>
        <app-receiver *ngFor="let receiver of receivers; let i = index" 
           [receiver]="receivers[i]" [receiversAmount]="receivers.length"
                [receiverIndex]="receivers.indexOf(receiver)" 
        (delete)="removeReceiver($event)"></app-receiver>
      </div>
   </form>
 </div>

测试时,我总是得到这个:

Expected [  ] to have size 3.

这是我的测试设置:

beforeEach(async () => {
TestBed.overrideProvider(Router, {useValue: {url: 'http://someurl.li'}});

await TestBed.configureTestingModule({
  declarations: [WichtelnGroupComponent, SenderComponent,
    ReceiverComponent, WichtelnDetailsComponent, ConfirmationComponent, 
     CheckConfirmationComponent],
  providers: [
    WichtelDataHandlerService
  ],
  imports: [FormsModule]
});
});

失败的测试:

  it('should create', () => {
    TestBed.overrideProvider(Router, {useValue: {url: 
    'http://someurl.li/dostuff'}});
     fixture = TestBed.createComponent(WichtelnGroupComponent);
     createComponents();
     expect(component).toBeTruthy();
     expect(component.receivers).toHaveSize(3);
     expect(document.getElementsByClassName('.sender')).not.toBeNull();
     expect(document.getElementsByClassName('.wichteln-group-form .form-group- 
      container app-sender')).not.toBeNull();
      const arr = Array.from(document.getElementsByClassName('.wichteln-group-form 
      ' +  '.form-group-container app-receiver'));
      expect(arr).toHaveSize(3);
     });

     function createComponents(): void {
      component = fixture.componentInstance;
      fixture.detectChanges();
      TestBed.compileComponents();
      }

如果我使用

结果是一样的
document.getElementsByClassName

expect(fixture.debugElement.queryAll(By.css('.wichteln-group-form .form-group- 
    container app-sender'))).toHaveSize(3);

正确的测试方法是什么?

queryAll returns 一个数组,您正在将一个数组与一个数字进行比较。

试试这个:

// check out .length here and check for app-receiver
// If app-receiver works, it means your CSS selector is not accurate
expect(fixture.debugElement.queryAll(By.css('app-receiver')).length).toBe(3);