Jeremy Jeremy - 2 months ago 24
Javascript Question

Using sinon to mock a date object

Here is my code:

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


I need to get that
startTime
in my unit test. From knowing unit testing in a java perspective, I would approach this problem as How can I mock the new date constructor? and then How can I mock the toLocaleTimeString function call?. However, I'm not sure that that's the way to approach this problem in javascript.

I've tried several things including sinon's useFakeTimers, but I don't think that's relevant as I'm not actually interested in the passage of time.

Here is my test code right now gleamed from lots of googling with zero context of how sinon works:

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


However, this gives the error "Attempted to wrap undefined property toLocaleTimeString as function".

Please help me understand the logic behind how I am meant to stub out this sort of functionality and how I do so.

Answer Source

You want to stub Date's prototype, so when you create a new Date it'll come with the stub:

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.