Mocking dates in AngularJS / Jasmine tests

后端 未结 4 1361
一个人的身影
一个人的身影 2021-02-05 01:19

I have a directive that initializes the Date object several times in several functions. When Unit testing the individual functions I can handle stubbing the date like this:

4条回答
  •  不知归路
    2021-02-05 02:02

    A straightforward solution would be to create an Angular Dates service that provides Date objects for you - it might even just have a single method - Dates.now() - that just sends back the current date by returning new Date(). You then use this service whenever something needs to get the current date.

    This then allows you to inject a different Dates service when unit testing, for example one that always returns a specific date of your choice when called, rather than the current time.

提交回复
热议问题