如何模拟Date对象?

时间:2013-07-10 14:58:36

标签: coffeescript jasmine

我正在尝试为此方法编写茉莉花测试

currentTime: ->
  Math.round(new Date().getTime()/1000)

在尝试这个测试中:

@date = new Date()
@date = Date(@date.getTime() + 70)
spyOn(window, "Date").andCallFake ->
  @date
expect(@user.currentTime()).toEqual xxx

我试过@date = new Date(@date.getTime() + 70),但我没有帮助。

但我收到了错误:

Uncaught TypeError: Object [object Object] has no method 'getTime'

知道怎么解决吗?感谢

2 个答案:

答案 0 :(得分:1)

你必须模拟Date构造函数,以便为getTime返回一个总是返回相同int的模拟器:

spyOn(window, "Date").andReturn {getTime: -> 1000}

答案 1 :(得分:0)

解决方案取自here

@_Date = Date
testContext = @
time = new Date().getTime() + 400
spyOn(window, "Date").andCallFake ->
  new testContext._Date(time)