Jasmine的模拟日期构造函数

Mock date constructor with Jasmine

本文关键字:构造函数 日期 模拟 Jasmine      更新时间:2023-09-26

我正在测试一个将日期作为可选参数的函数。我想断言,如果在没有参数的情况下调用函数,则会创建一个新的Date对象。

var foo = function (date) {
  var d = date || new Date();
  return d.toISOString();
}

如何断言调用了new Date

到目前为止,我有这样的东西:

it('formats today like ISO-8601', function () {
  spyOn(Date, 'prototype');
  expect().toHaveBeenCalled();
});

请参阅:https://github.com/pivotal/jasmine/wiki/Spies

来自茉莉花示例,

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

茉莉花日期

信用给@HMR。我写的测试是为了验证:

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

对我来说,它与一起工作

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

而不是.andCallFake(使用"grunt contrib jasmine":"^0.6.5",似乎包括jasmine 2.0.0)

对我来说,它只使用mockDate()而不使用其他任何东西:

jasmine.clock().mockDate(new Date('2000-01-01T01:01:01'));

这对我很有效

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

对于使用JasmineEdge版本的用户:

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