How to Stub Moment.js

December 7, 2015

We recently hit a problem when writing unit tests that included Moment.js. The library exports a factory rather than an object so it wasn’t obvious how to stub out its methods.

Our code looked similar to below…

import moment from 'moment'

export default class MyClass = {

  method() {
    const year = moment().format('YYYY')
    /* do something else */
  }

}

To find the solution I had to delve through Moment’s 3195 lines to find that it exposes its prototype using .fn. Here’s an example of how we stubbed out these methods using sinon and mocha.

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 */

})

← Fixing A Broken Keynote File 2016: Looking Forward →