angular:7如何在父组件上测试子发射器?

时间:2019-07-11 12:13:07

标签: javascript angular typescript

为事件发射器编写测试用例。为modelopen()方法编写测试用例

父ts文件 author-article-carousel.component.ts

public edit(row) {
    console.log(row);
    this.activeArticleService.getArticleDetail(row.id).subscribe((res: any) => {
      this.modalOpen(res);
    });
  }


  public modalOpen(value) {
    let config = {};
    config = {
      disableClose: true,
      maxWidth: '1050px',
      data: { value: value, user: 'author' }
    };
    if (this.dialogRef == null) {
      this.dialogRef = this.dialog.open(ArticleModalComponent, config);
    }
    this.dialogRef.afterClosed().subscribe(result => {
      console.log(`Dialog closed: ${result}`);
      this.dialogRef = null;
    });

    this.dialogRef.componentInstance.downloadreport.subscribe(response => {
      if (response) {
        this.activeArticleService.downloadReport(response).subscribe((response: HttpResponse<Blob>) => {
          this.activeArticleService.download(response, 'report.pdf');
        });
      }
    });
}

父HTML文件 author-article-carousel.component.html

<prism-article-carousel
  (clickOnTitle)="edit($event)"
></prism-article-carousel>

子HTML文件 article-carousel.component.html

 <div class="row">
            <div class="col-md-12">
              <a (click)="edit(item)" class="mat-card-title" style="cursor: pointer">{{ item.title }}</a>
            </div>

子ts文件 article-modal.component.ts

  public downloadReport(url) {
    this.downloadreport.emit(url);
  }

1 个答案:

答案 0 :(得分:1)

假设您具有有效的测试设置并为activeArticleService创建了有效的间谍

有两种方法取决于您使用的是浅层测试还是实际上已设置了声明所有组件的测试。 (我建议使用浅层测试方法,因为它只是一个单元测试)

使用浅层测试(设置NO_ERRORS_SCHEMA),您可以使用以下方法访问所需的元素来触发自定义EventHandler:

const debugElem = fixture.debugElement.query(By.css('prism-article-carousel'));
debugElem.triggerEventHandler('clickOnTitle', YOUR_EXPECTED_EVENT_OBJECT)
tick();

为此,您的测试需要使用fakeAsync

如果不使用此架构,您将使用

fixture.debugElement.query(By.css('prism-article-carousel'))

您将需要这样的内容(请注意,这只是伪代码)

childComponent = fixture.debugElement.query(By.css('prism-article-carousel')).componentInstance;
childComponent.emit(YOUR_VALUE_HERE);
tick();

请查看here in the official documentation,以获取有关测试嵌套组件的这些不同方法的更多信息。