我正在尝试在Angular中测试一个接收日期的服务函数,并检查该日期是否为将来的日期。如果是,则返回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;
}
Run Code Online (Sandbox Code Playgroud)
我该如何测试?因为如果我做这样的事情:
it('should return true if date is in the future', () => {
const date = '04/02/2018';
const result = service.checkDate(date);
expect(result).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)
今天它将过去,因为new Date()将会过去01/02/2018。但是,如果我下个月运行此测试,它将无法通过。
我可以将日期设置为将来要测试的日期,例如01/01/3018。但是我想知道是否还有另一种方法可以测试这种情况。