Mock date constructor with Jasmine

32,290

Solution 1

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();
  });

Solution 2

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

Solution 3

for me it worked with:

spyOn(Date, 'now').and.callFake(function() {
    return _currdate;
  });

instead of .andCallFake (using "grunt-contrib-jasmine": "^0.6.5", that seems to include jasmine 2.0.0)

Solution 4

this worked for me

var baseTime = new Date().getTime();
spyOn(window, 'Date').and.callFake(function() {
   return {getTime: function(){ return baseTime;}};
});

Solution 5

For me it worked by just using mockDate() without anything else:

jasmine.clock().mockDate(new Date('2000-01-01T01:01:01'));
Share:
32,290
Muhammad Hashir Anwaar
Author by

Muhammad Hashir Anwaar

I am a full stack Software Engineer on the web. Most of my work is remote and based in Australia. Over the course of my career, I have enjoyed working with talented engineering teams on a wide range of applications using different technologies. I have managed simple customer-facing applications and I have been fortunate to work with large teams on complex, high-budget, mission-critical code bases. I focus on delivering quality products that are functional, reliable, intuitive and that meet specifications. I am thorough, methodical in my work. I document, test and check what I do and I communicate effectively. I am creative, very strong in analytical problem-solving and I’m always evaluating my performance. I like mentoring and learning from other people. I believe I can cook a decent curry from scratch and I can bake bread without looking at the recipe.

Updated on August 17, 2021

Comments

  • Muhammad Hashir Anwaar
    Muhammad Hashir Anwaar almost 3 years

    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