Angular 5 单元测试使用新日期来检查日期

新手上路,请多包涵

我正在尝试在 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;
}

我该如何测试呢?因为如果我这样做:

 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 。但是如果我下个月运行这个测试,它不会通过。

我可以将要测试的日期设置得更远,例如 01/01/3018 。但我想知道是否有另一种方法来测试这种情况。

原文由 celsomtrindade 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 304
2 个回答

Date 可以模拟以明确测试它应该返回的值:

 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 Clock API 可用于模拟日期:

 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 调用可以断言的那样严格。

原文由 Estus Flask 发布,翻译遵循 CC BY-SA 3.0 许可协议

这有点老了,但我发现了一个替代解决方案,当我遇到类似问题时没有人提到过。我通过创建一个今天或现在的对象来创建一个日期,然后根据我的需要为其添加天数/年数。例如:

       const now = new Date()
      const yesterday = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() - 1
      )
      expect(functionThatReturnsTrueForFuture(yesterday)).toBeFalse()
      const tomorrow = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() + 1
      )
      expect(functionThatReturnsTrueForFuture(tomorrow)).toBeTrue()

对于可以将要比较的日期作为参数传递的情况(并且具有不依赖任何特定库的好处),这应该可以正常工作。

原文由 coppereyecat 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题