Mock date constructor with Jasmine

2019-02-16 05:08发布

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

5条回答
冷血范
2楼-- · 2019-02-16 05:46

this worked for me

var baseTime = new Date().getTime();
spyOn(window, 'Date').and.callFake(function() {
   return {getTime: function(){ return baseTime;}};
});
查看更多
时光不老,我们不散
3楼-- · 2019-02-16 05:58

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

查看更多
相关推荐>>
4楼-- · 2019-02-16 06:07

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)

查看更多
该账号已被封号
5楼-- · 2019-02-16 06:07

For the users who are using Edge version of Jasmine:

it('Should spy on Date', function() {
    var oldDate = Date;

    // and.callFake
    spyOn(window, 'Date').and.callFake(function() {
        return new oldDate();
    });

    var d = new Date().toISOString;

    expect(window.Date).toHaveBeenCalled();
});
查看更多
等我变得足够好
6楼-- · 2019-02-16 06:12

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();
  });
查看更多
登录 后发表回答