Constructor stub moment.js with Sinon

I cannot drown out the moment constructor when calling it using the format function to return a predefined string, here is an example specification that I would like to run using mocha :

 it('should stub moment', sinon.test(function() { console.log('Real call:', moment()); const formatForTheStub = 'DD-MM-YYYY [at] HH:mm'; const momentStub = sinon.stub(moment(),'format') .withArgs(formatForTheStub) .returns('FOOBARBAZ'); const dateValueAsString = '2025-06-01T00:00:00Z'; const output = moment(dateValueAsString).format(formatForTheStub); console.log('Stub output:',output); expect(output).to.equal('FOOBARBAZ'); })); 

I can see this output using console.log :

 Real call: "1970-01-01T00:00:00.000Z" Stub output: 01-06-2025 at 01:00 

But then the test does not give a result 01-06-2025 at 01:00 !== 'FOOBARBAZ' How can I close this moment(something).format(...) call correctly?

+7
momentjs mocha chai sinon
source share
1 answer

I found the answer at http://dancork.co.uk/2015/12/07/stubbing-moment/

Apparently, the moment provides a prototype using .fn , so you can:

 import { fn as momentProto } from 'moment' import sinon from 'sinon' import MyClass from 'my-class' const sandbox = sinon.sandbox.create() describe('MyClass', () => { beforeEach(() => { sandbox.stub(momentProto, 'format') momentProto.format.withArgs('YYYY').returns(2015) }) afterEach(() => { sandbox.restore() }) /* write some tests */ }) 
+10
source share

All Articles