I'm testing a function that takes a date as an optional argument. I want to assert that a new Date object is created if the function is called without the argument.
var foo = function (date) {
var d = date || new Date();
return d.toISOString();
}
How do I assert that new Date
is called?
So far, I've got something like this:
it('formats today like ISO-8601', function () {
spyOn(Date, 'prototype');
expect().toHaveBeenCalled();
});
See: https://github.com/pivotal/jasmine/wiki/Spies
To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime method. beforeAll(() => { jest. useFakeTimers("modern"); jest. setSystemTime(new Date(2022, 3, 1)); }); afterAll(() => { jest.
Mock Date object js const RealDate = Date; beforeEach(() => { global. Date. now = jest. fn(() => new Date('2019-04-22T10:20:30Z').
describe('testing dates in js', function () { beforeEach(() => { let today = moment('2016-01-01'). toDate(); jasmine. clock(). mockDate(today); }); it('should return the difference between today', () => { let date = moment('2016-01-05'); expect(4).
from jasmine example,
jasmine.clock().install();
var baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
jasmine.clock().tick(50)
expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
afterEach(function () {
jasmine.clock().uninstall();
});
jasmine date
Credit to @HMR. Test I wrote to verify:
it('Should spy on Date', function() {
var oldDate = Date;
spyOn(window, 'Date').andCallFake(function() {
return new oldDate();
});
var d = new Date().toISOString;
expect(window.Date).toHaveBeenCalled();
});
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