使用 sinon 模拟日期对象

Using sinon to mock a date object

这是我的代码:

var startTime = new Date(startDateTime).toLocaleTimeString("en-US", options);

我需要在单元测试中得到 startTime。从 java 的角度了解单元测试,我会将此问题视为 How can I mock the new date constructor? 然后 How can I mock the toLocaleTimeString 函数调用?。但是,我不确定这是在 javascript.

中解决此问题的方法

我已经尝试了几种方法,包括 sinon 的 useFakeTimers,但我认为这无关紧要,因为我实际上对时间的流逝不感兴趣。

这是我的测试代码,现在从大量谷歌搜索中闪现出来,其中关于 sinon 工作原理的上下文为零:

var whatever = sinon.spy(global, 'Date');
sinon.stub(whatever, 'toLocaleTimeString').yields('7:00 PM');

但是,这给出了错误 "Attempted to wrap undefined property toLocaleTimeString as function"。

请帮助我理解我打算如何去除这种功能以及我是如何做到的背后的逻辑。

您想对 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()

See the runkit example.

许多例子中的

None 对我有用(stubbing,useFakeTimers)。将它添加到我的测试套件中;

Date.prototype.toLocaleTimeString = sinon
    .stub()
    .callsFake(() => '7:00 PM');