Stub moment.js constructor with Sinon
It's hard to tell from the description, but if the reason you are trying to stub the moment constructor(but not the rest of the lib functionality) is because you are trying to control what date Moment returns (for more reliable testing), you can do this using Sinon's usefakeTimer
. Like so:
// Set up context for mocha test.
beforeEach(() => {
this.clock = date => sinon.useFakeTimers(new Date(date));
this.clock('2019-07-07'); // calling moment() will now return July 7th, 2019.
});
You can then update the date in the context of other tests that need to test the inverse logic around a specific date.
it('changes based on the date', () => {
this.clock('2019-09-12');
expect(somethingChanged).to.be.true;
});
Try adding this to your test suite if all else fails;
moment.prototype.format = sinon.stub().callsFake(() => 'FOOBARBAZ');
I found the answer at http://dancork.co.uk/2015/12/07/stubbing-moment/
Apparently moment exposes its prototype using .fn
, so you can:
import { fn as momentProto } from 'moment'
import sinon from 'sinon'
import MyClass from 'my-class'
const sandbox = sinon.createSandbox()
describe('MyClass', () => {
beforeEach(() => {
sandbox.stub(momentProto, 'format')
momentProto.format.withArgs('YYYY').returns(2015)
})
afterEach(() => {
sandbox.restore()
})
/* write some tests */
})