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 ]