这是我的代码:
var startTime = new Date(startDateTime).toLocaleTimeString("en-US", options);我需要在我的单元测试中得到那个startTime。通过了解java透视图中的单元测试,我会处理这个问题,因为我如何模拟新的日期构造函数?然后如何模拟toLocaleTimeString函数调用?但是,我不确定这是否是在javascript中解决这个问题的方法。
我尝试过一些东西,包括sinon的useFakeTimers,但我不认为这是相关的,因为我实际上对时间的推移并不感兴趣。
下面是我的测试代码,现在我的测试代码在大量googling中闪闪发光,没有说明sinon是如何工作的:
var whatever = sinon.spy(global, 'Date');
sinon.stub(whatever, 'toLocaleTimeString').yields('7:00 PM');但是,这会导致错误“试图将未定义的属性toLocaleTimeString包装为函数”。
请帮助我理解我是如何定义这类功能的背后的逻辑,以及我是如何做到的。
发布于 2017-08-16 21:51:08
您希望对Date的原型进行存根,所以当您创建一个新的Date时,它将附带存根:
const stub = sinon.stub(Date.prototype, 'toLocaleTimeString').returns('7:00 PM')
new Date().toLocaleTimeString("en-US")
stub.restore() // or Date.prototype.toLocaleTimeString.restore()https://stackoverflow.com/questions/45723379
复制相似问题