DEV Community

Robert Marshall
Robert Marshall

Posted on • Originally published at robertmarshall.dev on

How to Mock the Date in Redux Toolkit


This article was originally posted (and is more up to date) at https://robertmarshall.dev/blog/how-to-mock-the-date-in-redux-toolkit/


Redux Toolkit (RTK) was an absolute blessing when I finally got around to using it, rather than the old way of a million action creators and constant files. So much boilerplate work! However, it did come with some small issues that took some working out.

One of this issues was unit testing. For the most part Redux Toolkit makes testing very simple, but there is always that little edge case that creeps up when on a deadline. My particular issue was being unable to correctly test and mock dates within Redux Toolkit.

I had previously written an article on how to mock dates in Jest, and was pretty confident that Redux could be handled in the same way. This was not the case.

The Problem

My jest unit test was trying to make sure that a date ISO string was correctly set in the reducer. The slice creation looked like this:

const makeNewSlice = createSlice({
  name: "myNewSlice",
  initialState: {
    currentDate: new Date(Date.now()).toISOString()
  }
});
Enter fullscreen mode Exit fullscreen mode

However, as discussed in this github issue, the use of ‘new’ is a class instance and isn’t able to be serialized. Even mocking the date out seems to be ignored by RTK and throws the current computer date string. The test would always fail with the mocked date being incorrect.

The Solution

Create a helper function which returns the date string, and then mock that function file. Like so:

// util/dateHelper.js
export const getCurrentDateString = () => new Date(Date.now()).toISOString();

// state/features/mySlice.js
import { getCurrentDateString } from './util/dateHelpers';

const makeNewSlice = createSlice({
  name: "myNewSlice",
  initialState: {
    currentDate: getCurrentDateString()
  }
});
Enter fullscreen mode Exit fullscreen mode

The getCurrentDateString file can then be mocked out, and we can avoid having to handle any date/class mocking awkwardness.

Top comments (0)