使用新日期检查日期的Angular 5单元测试 [英] Angular 5 unit test using new Date to check date
问题描述
我正在尝试在Angular中测试一个接收日期的服务函数,并检查该日期是否为将来的日期.如果是,则返回true.
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();
});
今天它将过去,因为new Date()
将是01/02/2018
.但是,如果我下个月运行此测试,它将无法通过.
Today it will pass, because new Date()
will be 01/02/2018
. But if I run this test next month, it will not pass.
我可以将要测试的日期设置为将来的更远的日期,例如01/01/3018
.但是我想知道是否还有另一种方法可以测试这种情况.
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
可以模拟为肯定会返回的测试值:
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([...]);
...
或者,Jasmine 时钟 API可用于模拟日期:>
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
由于Date
不是间谍,所以测试不会像可以断言Date
调用那样严格.
Since Date
is not a spy, the test won't be as strict as the one where Date
calls can be asserted.
这篇关于使用新日期检查日期的Angular 5单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!