Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 unit test using new Date to check date

I'm trying to test a service function in Angular where it receives a date and check if the date is a date in the future. If it is, it returns true.

// The 'check_date' will always be in the format `dd/mm/yyyy`
public checkDate(check_date: string): boolean {
    const today: any = new Date();
    const dateParts: any = check_date.split('/');
    const dateObject: any = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);

    if (dateObject.getTime() > today.getTime()) {
        return true;
    }

    return false;
}

How can I test this? Because if I do something like this:

it('should return true if date is in the future', () => {
    const date = '04/02/2018';
    const result = service.checkDate(date);
    expect(result).toBeTruthy();
});

Today it will pass, because new Date() will be 01/02/2018. But if I run this test next month, it will not pass.

I could set the date to be test to be way further in the future, like 01/01/3018. But I'd like to know if there is another method to test this case.

like image 411
celsomtrindade Avatar asked Dec 07 '22 15:12

celsomtrindade


1 Answers

Date can be mocked to definitely test values it is supposed to return:

const UnmockedDate = Date;

spyOn(<any>window, 'Date').and.returnValues(
  new UnmockedDate('2018-01-01'),
  new UnmockedDate('2018-02-04')
);

const result = service.checkDate('04/02/2018');

expect(Date).toHaveBeenCalledTimes(2);

expect(Date.calls.all()[0].object instanceof UnmockedDate).toBe(true); // called with new
expect(Date.calls.argsFor(0)).toEqual([]);

expect(Date.calls.all()[1].object instanceof UnmockedDate).toBe(true);
expect(Date.calls.argsFor(1)).toEqual([...]);
...

Alternatively, Jasmine Clock API can be used to mock date:

jasmine.clock().install();
jasmine.clock().mockDate('2018-01-01');

const result = service.checkDate('04/02/2018');

...

jasmine.clock().uninstall(); // better be performed in afterEach

Since Date is not a spy, the test won't be as strict as the one where Date calls can be asserted.

like image 173
Estus Flask Avatar answered Dec 21 '22 23:12

Estus Flask