jest-mock-date-examples icon indicating copy to clipboard operation
jest-mock-date-examples copied to clipboard

Issue while setting up new Date()

Open soultrue opened this issue 5 years ago • 6 comments

Hi,

I am trying to mock new Date() but it is not working for me. It is giving below error: Type 'typeof Date' is not assignable to type 'DateConstructor'.

I tried with your below code: const getCurrentDate = () => new Date(); let realDate;


Using below code in my test spec:

realDate = Date; global.Date = class extends Date { constructor(...args) { if (args.length > 0) { // eslint-disable-next-line constructor-super, no-constructor-return return super(...args); }

    // eslint-disable-next-line no-constructor-return
    return currentDate;
  }
};

My requirement is, I am passing "new Date" in my method and getting back date/time with timezone offset like below: const deliveryDate = abc.getDeliveryDate(new Date()); deliveryDate = "2020-04-14T15:20:33.982-05:00"

I would like to fix or hard code new Date() so that I get same date and time(with offset) every time.

soultrue avatar Apr 14 '20 20:04 soultrue

@soultrue could you try using a regular function (instead of arrow)?

HugoDF avatar Apr 14 '20 20:04 HugoDF

@soultrue could you try using a regular function (instead of arrow)?

You mean like that: const getCurrentDate = function () { return new Date() }; }; ?

I tired above code but no luck, same error: Type 'typeof Date' is not assignable to type 'DateConstructor'.

soultrue avatar Apr 14 '20 21:04 soultrue

Wait is this a TypeScript issue?

HugoDF avatar Apr 14 '20 21:04 HugoDF

Yes

soultrue avatar Apr 14 '20 21:04 soultrue

const getCurrentDate = (function () { return new Date() };
} as any);

HugoDF avatar Apr 14 '20 21:04 HugoDF

No luck :(

Same error: Type 'typeof Date' is not assignable to type 'DateConstructor'.

Just to clarify, we are getting this error for "global.Date" in below code snippet.

global.Date = class extends Date { // getting error in this line Type 'typeof Date' is not assignable to type 'DateConstructor'. constructor(...args) { if (args.length > 0) { return super(...args); // Also getting error in this line - Type 'void' is not assignable to type 'Date'.ts

   }
};

soultrue avatar Apr 14 '20 21:04 soultrue