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?
it("should return decremented duration as time passes", () => { const timer = new Timer(5, true); jasmine. clock(). mockDate(new Date(startingTime + 1000)); expect(timer.
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(...
MomentJS is a widely used time and date formatting and calculation library.
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()); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With