Jasmine date mocking with moment.js

后端 未结 3 612
忘了有多久
忘了有多久 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:31

    I was trying to find an alternative to jasmine or even other mock frameworks to avoid dependencies.

    const currentToday = moment().toDate();
    console.log(`currentToday:`, currentToday)
    
    const newToday = moment('1980-01-01').toDate();
    console.log(`newToday    :`, newToday);
    
    Date.now = () => {
      return newToday
    };
    
    const fakedToday = moment().toDate();
    console.log(`fakedToday  :`, fakedToday)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    currentToday: 2019-09-17T15:26:12.763Z
    newToday    : 1980-01-01T00:00:00.000Z
    fakedToday  : 1980-01-01T00:00:00.001Z
    
    0 讨论(0)
  • 2021-02-18 14:37

    Check out how moment mock dates themselves in their own test suite: https://github.com/moment/moment/blob/2e2a5b35439665d4b0200143d808a7c26d6cd30f/src/test/moment/now.js#L15

    0 讨论(0)
  • 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());
    });
    
    0 讨论(0)
提交回复
热议问题