Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock date constructor with Jasmine

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

like image 686
Rimian Avatar asked Oct 02 '14 00:10

Rimian


People also ask

How do you mock a constructor like a new date?

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.

How do you mock a date object?

Mock Date object js const RealDate = Date; beforeEach(() => { global. Date. now = jest. fn(() => new Date('2019-04-22T10:20:30Z').

How do you test a jasmine date?

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).


2 Answers

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

like image 173
Anatoli Klamer Avatar answered Oct 07 '22 10:10

Anatoli Klamer


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();
  });
like image 11
Gordon Bockus Avatar answered Oct 07 '22 10:10

Gordon Bockus