首页 > 解决方案 > 当在 html 中进行方法调用时,使用 jasmine 对组件进行角度测试

问题描述

我必须测试这种奇怪的情况。在我的 html 中,我有:

    <div id="date">
      <h5>
        {{ showFormattedDate(myDate) }}
      </h5>
    </div>

函数showFormattedDate()定义.ts如下:

  showFormattedDate(dateToFormat: string): string {
    return moment(dateToFormat).format('HH:mm DD/M/YYYY');
  }

现在我正在尝试对此进行测试,但我不断收到此错误:

预计“在无效日期创建”为“12:23 29/5/2020”。

无效的日期部分也是我在页面加载时在屏幕上看到的一秒钟,但我认为这是因为函数调用。

我尝试使用以下两种方式对其进行测试:

  it('should display the date correctly', async () => {
    fixture.detectChanges();
    // await fixture.whenStable();
    // await fixture.isStable();
    // await fixture.whenRenderingDone();

    expect(el.query(By.css('#date')).nativeElement.textContent).toContain(
      getTestData().date);
  });

  it('should display the date correctly (async)', async(() => {
    fixture.detectChanges();

    fixture.whenStable().then(() => {
      // wait for async getQuote
      fixture.detectChanges(); // update view with quote
      expect(el.query(By.css('#date')).nativeElement.textContent).toContain(getTestData().date);
    });
  }));

但两者都返回上述错误。我怎么能解决这个问题?

标签: angularunit-testingkarma-jasmineangular-test

解决方案


在模板表达式中调用方法在 Angular 中被认为是不好的做法。因此您可能希望首先避免这种情况。

阅读内容以获取更多详细信息。

您可以在此处使用 Angular Pipe,它将您的日期转换为您想要的格式,您可以测试管道的转换方法。

有关使用 Angular 管道的更多详细信息,请单击此处并了解如何在此处测试您的 Angular 管道,这是一篇很好的文章


推荐阅读