Javascript 用 Jasmine 模拟日期构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26152796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:25:00  来源:igfitidea点击:

Mock date constructor with Jasmine

javascriptmockingjasmine

提问by Rimian

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.

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

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

How do I assert that new Dateis called?

我如何断言它new Date被称为?

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

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

采纳答案by Gordon Bockus

Credit to @HMR. Test I wrote to verify:

归功于@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();
  });

回答by Anatoli Klamer

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

茉莉花枣

回答by cesarpachon

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)

而不是.andCallFake(使用“grunt-contrib-jasmine”:“^0.6.5”,这似乎包括茉莉花2.0.0)

回答by scb

this worked for me

这对我有用

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

回答by Jeff Tian

For the users who are using Edge version of Jasmine:

对于使用 Edge 版本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();
});