Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine date mocking with moment.js

Tags:

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?

like image 934
jacwah Avatar asked Oct 27 '15 23:10

jacwah


People also ask

How to mock date in jasmine?

it("should return decremented duration as time passes", () => { const timer = new Timer(5, true); jasmine. clock(). mockDate(new Date(startingTime + 1000)); expect(timer.

How do you mock a moment date?

mockImplementation(() => new Date('2019-01-01')); // Test code here Date. now. mockRestore(); // Mocking out Date constructor object (used by moment) const nowString = '2018-02-02T20:20:20'; // Mock out the date object to return a mock null constructor const MockDate = (lastDate) => (... args) => new lastDate(...

Is moment JS still used?

MomentJS is a widely used time and date formatting and calculation library.


1 Answers

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()); }); 
like image 138
jacwah Avatar answered Sep 22 '22 14:09

jacwah