Mocking dates in AngularJS / Jasmine tests

后端 未结 4 1355
一个人的身影
一个人的身影 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:01

    Jasmine (2.2) Clock can mock dates and time.

    http://jasmine.github.io/2.2/introduction.html#section-Mocking_the_Date

    For example (from the docs):

    it("mocks the Date object and sets it to a given time", function() {
      var baseTime = new Date(2013, 9, 23);
      jasmine.clock().mockDate(baseTime);
    
      jasmine.clock().tick(50);
      expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
    });
    

提交回复
热议问题