skip to Main Content

I’m wondering if anyone has been able to implement something like jest.spyOn(global, 'Date').mockImplementation(() => now); inside of Deno.

I have looked through the documentation for the mock in the Deno documentation here and I have looked through the mock time here however this doesn’t look like it will replace the new Date() with the mocked implementation.

2

Answers


  1. You can overwrite any global variable directly — they’re accessible as properties/methods on globalThis.

    Here’s an example (that’s not specific to any testing framework) which replaces the global Date class with an example class that also has a method named toString:

    class Example {
      toString() {
        return "This is just an example";
      }
    }
    
    function overwriteDateAndReturnRestoreFn() {
      const originalDate = globalThis.Date;
      globalThis.Date = Example;
      return () => void (globalThis.Date = originalDate);
    }
    
    console.log(new Date().toString()); //=> <A string represetning the actual current date>
    
    const restore = overwriteDateAndReturnRestoreFn();
    console.log(new Date().toString()); //=> "This is just an example"
    
    restore();
    console.log(new Date().toString()); //=> <A string represetning the actual current date>
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search