【问题标题】:Mock only today's date in Jasmine unit test仅在 Jasmine 单元测试中模拟今天的日期
【发布时间】:2016-01-27 17:20:00
【问题描述】:

我正在为比较日期的函数编写 Jasmine 单元测试。我想提供一个假日期用于今天的日期。因此,我正在监视 window 对象上的 Date 方法并返回预定义的日期。

这很好用,但是在我正在测试的函数中,我还从字符串中读取日期并调用new Date(yyyy, mm, dd) 将它们转换为日期。发生这种情况时,这些值将替换为我提供的模拟日期。

这是一个例子:

var checkDate = function () {
            return { today: new Date(), anotherDay: new Date(2016, 0, 1) }
        };

var createDate = function (year, month, date) {
  var overrideDate = new Date(year, month, date);
  spyOn(window, 'Date').andCallFake(function () {
    return overrideDate;
  })
}

var dates;

describe("checkDate", function() {
  beforeEach(function() {
    createDate(2015, 11, 1);
    dates = checkDate();
  })
  it("today has a value of 12/1/2015", function() {
    expect(dates.today.toLocaleDateString()).toBe('12/1/2015');
  });
  it("anotherDay has a value of 1/1/2016", function() {
    expect(dates.anotherDay.toLocaleDateString()).toBe('1/1/2016');
  })
});

Here's a JSFiddle example of the issue.

我怎样才能只模拟今天的日期,并允许new Date(yyyy, mm, dd) 创建正确的日期对象?我希望小提琴通过中的两个测试,即anotherDay 设置为1/1/2016today 设置为12/1/2015

Karma-Jasmine v 0.1.6。

【问题讨论】:

    标签: javascript angularjs jasmine


    【解决方案1】:

    最好使用Jasmine Clock API

    beforeEach(() => {
      const fixedDate = new Date(2020, 0, 1);
      jasmine.clock().install();
      jasmine.clock().mockDate(fixedDate);
    });
    
    afterEach(() => {
      jasmine.clock().uninstall();
    });
    

    src:https://stackoverflow.com/a/48574541

    【讨论】:

      【解决方案2】:

      您可以缓存window.Date,以便在将参数传递到您的模拟时使用它

      var windowDate = window.Date;
      spyOn(window, 'Date').andCallFake(function (year,month,day) {
          if(year != undefined && month != undefined && day != undefined){
              return new windowDate(year,month,day);
              }
        return overrideDate;
      })
      

      https://jsfiddle.net/n3Lf0g8p/1/

      【讨论】:

        猜你喜欢
        • 2013-06-09
        • 1970-01-01
        • 1970-01-01
        • 2020-04-05
        • 2011-01-29
        • 2017-05-10
        • 2013-07-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多