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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With