Jasmine date mocking with moment.js

后端 未结 3 611
忘了有多久
忘了有多久 2021-02-18 14:07

I\'m using moment.js for date/time in my application, but it seems like it doesn\'t play well with Jasmine\'s mocking capabilities. I\'ve put together a test suite below that sh

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-18 14:44

    jasmine.clock().mockDate expects Date as input. Date and moment are not fully compatible. If you provide the to-be-mocked date in the spec itself you could simply use Date there instead.

    If your code generates a moment you want to mock, or you'd rather use the moment API, take a look at moment.toDate(). This method returns the Date object backing a moment.

    it('uses the mocked time with moment', function() {
        var today = moment('2015-10-19').toDate();
        jasmine.clock().mockDate(today);
        expect(moment().valueOf()).toEqual(today.valueOf());
    });
    

提交回复
热议问题