jasmine spyOn on javascript new Date

use*_*376 5 javascript unit-testing jasmine angularjs karma-jasmine

我在angulajs中对我的客户端代码进行单元测试,我理解这段代码意味着

 var newdate = new Date(2013,6,29);
    spyOn(Date.prototype, 'getTime').and.callFake(function() {
          return newdate;
        });
Run Code Online (Sandbox Code Playgroud)

我们模拟Date对象的getTime()方法.但我想模仿新的Date()而不是.例如,我想测试的代码包含这一行

payload.created_at = new Date();
Run Code Online (Sandbox Code Playgroud)

我没有访问payload.created_at.所以我想告诉茉莉每当你看到新的Date()时,用我给你的给定日期替换它.所以我在考虑类似但不起作用的东西.

spyOn(Date.prototype, 'new Date').and.callFake(function() {
          return newdate;
        });
Run Code Online (Sandbox Code Playgroud)

但是新日期不是日期的方法.请有人帮我解决这个问题吗?谢谢

joh*_*ase 12

茉莉花时钟 API允许你伪造了JavaScript的日期功能,无需手动编写间谍吧.

特别是,请阅读有关模拟日期的部分.

describe("Mocking the Date object", function(){
    beforeEach(function() {
      jasmine.clock().install();
    });

    it("mocks the Date object and sets it to a given time", function() {
      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();
    });
});
Run Code Online (Sandbox Code Playgroud)


use*_*376 1

所以这个链接[ Mock date constructor with Jasmine有答案,但由于某种原因它对我不起作用。我想这可能与我的茉莉花版本有关,但下面是对我有用的代码

var oldDate = new Date();
    spyOn(window, 'Date').and.callFake(function() {
      return oldDate;
    });
Run Code Online (Sandbox Code Playgroud)

上面代码的 .and.callFake 和上面链接中的 .and.callFake 是有区别的。谢谢