Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Handling More Than One Date Object in Jest Tests

I am trying to prepare a Date object mock to make the time constant and test it. I don't know how to test if I have more than one Date object declared in the function I want to test. For example, in the following code, the function dayRange returns a range of one day. If you provide the following mock when testing, the function dayRange will look like the one in the code.

export const dayRnage = (): [Date, Date] => {
  const begin = new Date();
  begin.setHours(0);
  begin.setMinutes(0);
  begin.setSeconds(0);
  begin.setMilliseconds(0);

  const end = new Date(begin);
  end.setDate(begin.getDate() + 1);
  end.setMilliseconds(-1);

  return [begin, end];
};

We cannot handle more than one Date object because the mock returns the same object! How can I handle the Date objects separately?

describe("smaple test", () => {
  beforeEach(() => {
    const mockDate = new Date("2021-09-26T00:00:00.000Z");
    jest.spyOn(global, "Date").mockImplementation((): any => {
      return mockDate;
    });
  });

  test("test", () => {
    console.log(dayRnage());
  });
});

// result =>  [ 2021-09-26T14:59:59.999Z, 2021-09-26T14:59:59.999Z ]
// expect =>  [ 2021-09-25T15:00:00.000Z, 2021-09-26T14:59:59.999Z ]

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!