Jasmine date mocking with moment.js

I use moment.js for the date / time in my application, but it does not seem to play well with the mocking capabilities of Jasmine. I put together a test suite below that shows my problem:

jasmine.clock().mockDate doesn't seem to work for a minute 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 is Date working as expected and moment not working? Doesn't moment use Date under the hood?

What is the right way to fake moment with Jasmine?

+19
javascript momentjs jasmine
source share
3 answers

jasmine.clock().mockDate waiting for Date entered. Date and moment not fully compatible. If you specify a date that will laugh at the specification itself, you can simply use Date instead.

If your code generates a moment that you want to make fun of, or you prefer to use the moment API, see moment.toDate() . This method returns a Date object that supports the 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()); }); 
+34
source share

Check how fictitious moments suit themselves in their own test suite: https://github.com/moment/moment/blob/2e2a5b35439665d4b0200143d808a7c26d6cd30f/src/test/moment/now.js#L15

0
source share

I tried to find an alternative to jasmine or even other dummy 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
source share

All Articles