Jasmine date mocking with moment.js

天大地大妈咪最大 提交于 2019-12-05 09:52:53

问题


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 shows my issue:

jasmine.clock().mockDate doesn't seem to work for moment, while it works fine for Date.

describe('Jasmine tests', function () {
    beforeEach(function() {
        jasmine.clock().install();
    });

    afterEach(function() {
        jasmine.clock().uninstall();
    });

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


    // Fail
    it('uses the mocked time with moment', function() {
        var today = moment('2015-10-19');
        jasmine.clock().mockDate(today);

        expect(moment().valueOf()).toEqual(today.valueOf());
    });
});

Why does Date work as expected while moment does not? Isn't moment using Date under the hood?

What is the right way to mock moment using Jasmine?


回答1:


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());
});



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/33380311/jasmine-date-mocking-with-moment-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!