Mocking Moment.js in Jest — A Simple, One-Line Solution

David Good
Frontend Weekly
Published in
2 min readJan 30, 2018

First Unit Test

Mocking a component’s call to Moment.js seems like a great candidate for our first unit test in Jest. However, it‘s not as straightforward as you might think. You could use a manual mock placed in a __mocks__ directory. But that’s not very elegant. Here, we show a simple, one-line solution in a basic test scenario.

Stateless Functional Component

To get started, we have a stateless functional component which calls Moment.js to get the current timestamp.

import React from 'react';
import moment from 'moment';
const Clock = () => {
return (<h1>{moment().format()}</h1>);
};
export default Clock;

Snapshot Test Case with Mock

We use React Test Renderer to compare the component to the previous snapshot. If we don’t mock the Moment.js call, the timestamp will change each time the test runs, and the test will fail.

The Jest documentation states:

jest.mock(path, moduleFactory) takes a module factory argument. A module factory is a function that returns the mock.

Therefore, the second argument to jest.mock needs to be a function (first arrow function) which returns a another function which corresponds to the moment() call (second arrow function). This returns an object with one element, the format function, which returns a fixed, arbitrary timestamp when called.

import React from 'react';
import renderer from 'react-test-renderer';
import Clock from '../../component/Clock';
// Return a fixed timestamp when moment().format() is called
jest.mock('moment', () => () => ({format: () => '2018–01–30T12:34:56+00:00'}));
it('matches snapshot', () => {
const tree = renderer.create(<Clock />).toJSON();
expect(tree).toMatchSnapshot();
});

Same Test Case using Shallow Renderer

There are a lot of options available for shallow rendering React components, but the React Test Renderer’s shallow renderer works just fine and doesn’t require additional config or dependencies. This is the same test case as above except for the use of the shallow renderer.

import React from 'react';
import ShallowRenderer from 'react-test-renderer/shallow';
import Clock from '../../component/Clock';
// Return a fixed timestamp when moment().format() is called
jest.mock('moment', () => () => ({format: () => '2018–01–30T12:34:56+00:00'}));
it('matches snapshot', () => {
const renderer = new ShallowRenderer();
const component = renderer.render(<Clock />);
expect(component).toMatchSnapshot();
});

--

--

David Good
Frontend Weekly

Software engineer crafting full-stack, cloud-native solutions for enterprise