【问题标题】:angular testing a component using jasmine when the a method call is made in the html当在 html 中进行方法调用时,使用 jasmine 对组件进行角度测试
【发布时间】:2020-05-29 17:41:12
【问题描述】:

我必须测试这种奇怪的情况。在我的 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);
    });
  }));

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

【问题讨论】:

    标签: angular unit-testing karma-jasmine angular-test


    【解决方案1】:

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

    阅读this了解更多详情。

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

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

    【讨论】:

    • 我想使用 MomentJS,所以我不必摆弄日期,但如果我要使用管道,我似乎需要这样做?
    • 您可以将您在此处的日期逻辑移动到管道的转换方法中
    • 你以前做过吗?我刚刚完成了制作自己的管道的过程,它再次在页面中工作,但出现错误。错误:找不到管道“customDate”!所以任何帮助将不胜感激
    • 您是否使用 Angular ng 命令生成了您的管道? ng generate pipe &lt;your pipe name&gt;
    • 这是正确的方式,你在声明数组中看到app.module.ts 中的管道类条目吗?
    猜你喜欢
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2020-05-30
    相关资源
    最近更新 更多