Angular Testing, are there better ways to write this code?

I’m learning Angular testing, but can’t seem to find any good resources on if I’m doing this the proper way.

In my spec file, I am running a function setDashboardGreeting(hours) but this does the same thing as the function as I already have in my component: getTime(). Is there a way I can use the same function so I don’t have to re-write it in my test?

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');
    });
  });
});

And then in my component, I have this function:


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';
}

Do I need to re-write the if/else statement in my test or if this possible to use the getTime() function from my component?

Source: New feed
Source Url Angular Testing, are there better ways to write this code?