Categories
JavaScript Answers

How to mock a constructor with Jest and JavaScript?

Spread the love

To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime method.

For instance, we write

beforeAll(() => {
  jest.useFakeTimers("modern");
  jest.setSystemTime(new Date(2022, 3, 1));
});

afterAll(() => {
  jest.useRealTimers();
});

to call useFakeTimers to use a mock timer.

Then we call setSystemTime to set the date and time in the test environment.

We make the calls in the beforeAll callback to run the code before any tests are run.

Then in the afterAll callback, we call useRealTimers to clear the mocked timers and use the real ones.

Conclusion

To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *