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

David Good
Jan 30, 2018 · 2 min read

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();
});

Frontend Weekly

It's really hard to keep up with all the front-end…

David Good

Written by

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

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

David Good

Written by

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

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store