0

Scratching my head trying to figure out why myDate is not an instanceof Date.

Can anyone explain? Is there any other debugging things I can try?

//Defined in some other module
myDate = new Date();

// console.log output:
console.log(myDate);                   // 2019-11-17T05:00:00.000Z
console.log(typeof myDate);            // object   ✅
console.log(myDate instanceof Object); // true     ✅
console.log(myDate.constructor);       // [Function: Date] ✅
console.log(myDate instanceof Date);   // false 
skube
  • 5,867
  • 9
  • 53
  • 77
  • 2
    What browser/runtime are you using? I get the following result when using latest Chrome. `myDate = new Date(); myDate instanceof Date // true` – Mark Skelton Nov 30 '19 at 16:12
  • 1
    I've replaced your example with a snippet and that shows the expected behavior (`myDate instanceof Date === true`). You will have to add more info on your setup. – Andreas Nov 30 '19 at 16:17
  • There's lots of discussion in this question: https://stackoverflow.com/questions/643782/how-to-check-whether-an-object-is-a-date – Matt U Nov 30 '19 at 16:17
  • Yeah, when I try it outside my setup as well, I get expected results. Was hoping it was something silly. I'll have to see if I can figure out a a minimal test example of my setup. – skube Nov 30 '19 at 16:34
  • What exactly does "*Defined in some other module*" mean? What kind of modules are you using, how are they loaded, any chance that it runs in a different realm? Btw, even if `myDate.constructor.name == "Date"` I bet that `myDate.constructor != Date` – Bergi Nov 30 '19 at 17:16
  • It's hard to trace as the object is being passed around but `myDate.constructor != Date` logs `true` (tho eslint complains) – skube Nov 30 '19 at 17:37
  • I've added console.log of `myDate` to ques. above if it helps any. In answer to the above questions, I'm running a Create React App in Node (v13.1.0) environment with TypeScript. No browser. – skube Nov 30 '19 at 17:41
  • Those are the direct console logs and — I agree — it makes no sense. However, isn't the idea to troubleshoot things that don't make sense so we can learn? Closing won't help that endeavour. – skube Nov 30 '19 at 20:14

1 Answers1

0

The culprit was that this was occurring within a test suite, which was attempting to mock or override the global Date object

    global.Date = class extends Date {
      constructor() {
        super();
        return constantDate;
      }
    };

Hence the weird behaviours.

skube
  • 5,867
  • 9
  • 53
  • 77