Angular Testing,有没有更好的方法来编写此代码?

时间:2019-12-20 23:15:06

标签: angular

我正在学习Angular测试,但是如果我以正确的方式进行操作,似乎找不到任何好的资源。

在我的规范文件中,我正在运行一个函数setDashboardGreeting(hours),但此功能与组件getTime()中已经具有的功能相同。有没有办法可以使用相同的功能,所以我不必在测试中重新编写它?

describe('TestComponent', () => {
  let component: TestComponent;
  let dashboardGreeting;
  let hours;
  function setDashboardGreeting() {
    if (hours < 5) component.dashboardGreeting = 'Morning';
    else if (hours < 10) component.dashboardGreeting = 'Afternoon';
    else component.dashboardGreeting = 'Evening';
  }

  beforeEach(() => {
    dashboardGreeting = '';
    component = new TestComponent();
  });

  describe('DashboardGreeting', () => {
    it('should return Morning', () => {
      let hours = 10
      setDashboardGreeting();

      expect(component.dashboardGreeting).toBe('Good Morning');
    });
  });
});

然后在我的组件中,我具有以下功能:


getTime() {
  const now = new Date();
  const hours = now.getHours();

  if (hours < 5) this.dashboardGreeting = 'Morning';
  else if (hours < 10) this.dashboardGreeting = 'Afternoon';
  else this.dashboardGreeting = 'Evening';
}

我是否需要在测试中重新编写if / else语句,或者是否有可能使用组件中的getTime()函数?

1 个答案:

答案 0 :(得分:1)

一种简化测试并减少重复的方法是使日期(单元代码中的日期(代码中的now)可以通过单元测试传递。例如:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  salutation = '';

  ngOnInit(): void {
    this.salutation = this.getSalutation(new Date());
  }

  getSalutation(date: Date): string {
    const hours = date.getHours();

    if (hours < 5)
      return 'Good Morning';
    else if (hours < 10)
      return 'Good Afternoon';
    else
      return 'Good Evening';
  }
}

请注意,我将getDate重命名为getSalutation。我还使它返回了一个值(get),而不是 set 一个值。

然后,通过测试,您可以调用带有各种日期的getSalutation来检查称呼是否符合预期。您还可以检查在调用salutation时是否设置了ngOnInit,以及ngOnInit使用间谍使用getSalutation实例调用Date的情况。

相关问题