When Extending the TypeScript Date Object Doesn't Play Nice with zone.js

I recently ran into an issue while upgrading an application from Angular 4 to Angular 13. It's been a monster of a project, made more complex by the fact that the app originally did not use the Angular CLI.

One of the developers had introduced some extensions to TypeScript's Date object, to add additional methods to it, 2 of which were static. It's debatable whether or not this is a good approach, and you'll find many opinions online from those that don't like this approach. It's not one I'm comfortable with myself. But all was working fine until the upgrade.

Once everything had been upgraded to Angular 13 and the latest version of TypeScript however, many of the unit tests that reference these methods (particularly one of the static ones we used frequently) began failing, saying that the method didn't exist. I verified everything was being imported correctly. It was working fine in another, up-to-date app, and I even set up a quick, working example in a fresh app. So what was wrong here?

I finally narrowed the issue down to tests which were in the fakeAsync zone. Normally, this is what Date is:

But under the fakeAsync zone, it looked like this:


Doing some digging, I found a pull request from 3 years ago that adds the ability to prevent this from happening if you don't want it to. After learning of that, I was able to implement the code below in a beforeEach() in the effected tests to prevent the issue:

      const global = window as any;
      let disableDatePatchingKey = Zone.__symbol__('disableDatePatching');
      global[disableDatePatchingKey] = true;

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4