Commit graph

44 commits

Author SHA1 Message Date
Andrew Scott
ced2fa5253 refactor(zone.js): Improve missing proxy zone error for jest imported (#64497)
test functions

This improves the fakeAsync error message when importing it, describe,
etc from jest

We will not be further expanding the ZoneJS patches to support
additional use-cases.

fixes #47603

PR Close #64497
2025-10-22 23:26:23 +00:00
Rahul Kamat
a943e7cb05 refactor(core): Update async-test.ts to use globalThis polyfill (#57505)
This updates async-test to use globalThis instead of what it was using.

PR Close #57505
2025-09-16 15:10:04 +00:00
Andrew Scott
0a827f9284 refactor(zone.js): Add internal implementation for auto ticking fakeAsync (#62135)
Benefits of auto-ticking mock clocks have been described in other PRs,
such as https://github.com/jasmine/jasmine/pull/2042 and
https://github.com/sinonjs/fake-timers/pull/509. In short, `fakeAsync`
cannot work when some tasks are required to be truly async, such as XHRs
or observers like ResizeObserver. In addition, auto ticking mock clocks
can be applied to tests without the tests then needing to update
everything to manually flush timers.

PR Close #62135
2025-08-08 08:39:24 -07:00
Andrew Scott
3c216c1ec6 fix(zone.js): waitForAsync should pass args to the test function (#61755)
This ensures that test functions with arguments (e.g. `it.each` in jest)
are forwarded to the test function. This does not apply to jasmine,
which assumes the only arguments needed would be the `done` function.

fixes #61717

PR Close #61755
2025-06-09 11:22:22 -07:00
Andrew Scott
1ea39e050c refactor(zone.js): Add a withProxyZone helper that might be used for unpatched test frameworks (#61626)
As an alternative to monkey patching vitest, this change adds a method that could be used
for manually running functions inside a shared proxy zone. If used inocrrectly,
this would mean that
the `fakeAsync` closure may not capture all timers and microtasks if it
invokes things created in a zone that was already forked (e.g. creating
a component in a beforeEach:
2699dd6555/packages/zone.js/lib/jasmine/jasmine.ts (L363-L371))

PR Close #61626
2025-05-22 13:39:30 -07:00
Andrew Scott
962b59b14e fix(core): Ensure ComponentFixture does not duplicate error reporting from FakeAsync (#60104)
When using `fakeAsync`, if errors happen inside the Angular zone, they
are also handled by the fakeAsync machinery. Rethrowing errors from the
`NgZone.onError` subscription is not appropriate in this case because it
results in the error being thrown twice.

db2f2d99c8/packages/zone.js/lib/zone-spec/fake-async-test.ts (L783-L784)
db2f2d99c8/packages/zone.js/lib/zone-spec/fake-async-test.ts (L473-L478)

PR Close #60104
2025-02-26 11:56:18 -05:00
Joey Perrott
9dbe6fc18b refactor: update license text to point to angular.dev (#57901)
Update license text to point to angular.dev instead of angular.io

PR Close #57901
2024-09-24 15:33:00 +02:00
Andrew Scott
70e8b40750 fix(zone.js): Update the default behavior of fakeAsync to flush after the test (#57240)
From the internal issue on the matter:

> When using the standard Jasmine version of it promises returned by the body function are automatically awaited. The Catalyst version of it is fake-async, so awaiting the promise does not make sense; however it would be nice if Catalyst automatically flushed the promise to replicate the experience of using standard it. This would allow users to do the following:

```
it('should fail later', async () => {
  await new Promise(r => setTimeout(r));
  fail('failure');
});
```
> In Catalyst today the above test will pass. If this proposal to automatically flush the resulting promise were implemented it would fail.

Flushing after the tests complete has been the default behavior inside
Google since 2020. Very few tests remain that use the old behavior of
only flushing microtasks. The example above would actually fail with
`fakeAsync` due to the pending timer, but the argument still remains the
same. We might as well just flush if we're going to fail the test
anyways by throwing if there's no flush at the end.

BREAKING CHANGE: `fakeAsync` will now flush pending timers at the end of
the given function by default. To opt-out of this, you can use `{flush:
false}` in options parameter of `fakeAsync`

PR Close #57240
2024-08-05 20:24:54 +00:00
Andrew Scott
99d679d606 feat(zone.js): Add 'flush' parameter option to fakeAsync to flush after the test (#57137)
From the internal issue on the matter:

> When using the standard Jasmine version of it promises returned by the body function are automatically awaited. The Catalyst version of it is fake-async, so awaiting the promise does not make sense; however it would be nice if Catalyst automatically flushed the promise to replicate the experience of using standard it. This would allow users to do the following:

```
it('should fail later', async () => {
  await new Promise(r => setTimeout(r));
  fail('failure');
});
```
> In Catalyst today the above test will pass. If this proposal to automatically flush the resulting promise were implemented it would fail.

Flushing after the tests complete has been the default behavior inside
Google since 2020. Very few tests remain that use the old behavior of
only flushing microtasks. The example above would actually fail with
`fakeAsync` due to the pending timer, but the argument still remains the
same. We might as well just flush if we're going to fail the test
anyways by throwing if there's no flush at the end.

PR Close #57137
2024-08-02 16:52:07 +00:00
Joey Perrott
f307e95459 refactor: migrate zone.js to prettier formatting (#55427)
Migrate formatting to prettier for zone.js from clang-format

PR Close #55427
2024-04-29 09:52:05 -07:00
JiaLiPassion
ddbf6bb038 fix(zone.js): make sure fakeasync use the same id pool with native (#54600)
Close #54323

fakeAsync should use the same timerId pool with native, so they will not
conflict.

PR Close #54600
2024-03-28 10:30:25 -07:00
Doug Parker
54a1fe05df refactor(zone.js): fix fake async test by reading parentUnresolved symbol lazily (#53443)
As this was, `__symbol__` was being called as a static field initializer, which runs during module evaluation, meaning it happened at import time. However for tests, the Zone prefix is overridden which changes the result of `__symbol__`. This change happens too late to be picked up by `__symbol__` at top-level execution, so instead we defer it until `symbolParentUnresolved` is actually read.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
b334e29d59 refactor(zone.js): read patched timers after they are patched (#53443)
This moves timer patching from a top-level side effect into the `patchFakeAsyncTest` function. Top-level statements are evaluated before the Node patches run and have a chance to patch them with the Zone versions of these timers, meaning `FakeAsyncTestZoneSpec` was repatching the native versions between tests. The fix here is to grab the patched versions of these timers during the `patchFakeAsyncTest` function where we can be confident Node patches have already run.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
6ca1911967 refactor(zone.js): export fake-async-test.ts functions (#53443)
This moves the internals of `fake-async-test.ts` outside `patchFakeAsyncTest` and exports them. This way they can be imported without depending on the top-level side effects of loading Zone.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
33c08e5aba refactor(zone.js): switch async-test.ts to use __symbol__ from an import (#53443)
This removes a dependency on the top-level side effect of `Zone` global initialization.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
181121dd9e refactor(zone.js): rename __global variable (#53443)
For some reason the `_global` name appears to conflict with another `_global` name. Not entirely sure how or why, but the easiest fix seems to be to just give the variable a unique name.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
73969ae9d4 refactor(zone.js): extracts TaskTrackingZoneSpec and exports it (#53443)
While `TaskTrackingZoneSpec` was implicitly global previously, it does not need to be exposed in a `declare global {}` block. This is because classic scripts in TypeScript are only implicitly global within the same compilation. `TaskTrackingZoneSpec` was not exposed in the existing `.d.ts` files shipped with the `zone.js` package. Within google3, this is also a separate compilation and was not accessible. As a result, `TaskTrackingZoneSpec` was always private and we do not need a global to maintain compatibility.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
cf61126ef3 refactor(zone.js): extracts ProxyZoneSpec and exports it (#53443)
While `ProxyZoneSpec` was implicitly global previously, it does not need to be exposed in a `declare global {}` block. This is because classic scripts in TypeScript are only implicitly global within the same compilation. `ProxyZoneSpec` was not exposed in the existing `.d.ts` files shipped with the `zone.js` package. Within google3, this is also a separate compilation and was not accessible. As a result, `ProxyZoneSpec` was always private and we do not need a global to maintain compatibility.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
1b9c807efa refactor(zone.js): update Zone bundles to call patch* functions (#53443)
Since each patch no longer contains top-level side effects, each bundled entry point needs to import and call its associated patch. For the most part this just means that each entry point imports the associated patch and invokes it at the top-level scope.

Note that many of these entry points did not actually have a dependency on `Zone` and had no guarantee that it was loaded prior to execution. To maintain consistency, the missing dependencies on `Zone` are left as-is. They will use the global instance of `Zone` and if users fail to load it prior to importing a specific patch, then the patch will fail just as it did previously.

PR Close #53443
2024-03-15 18:11:33 -07:00
Doug Parker
7c1991048b refactor(zone.js): wrap Zone.__load_patch calls in exported functions (#53443)
This removes top-level side effects from each of these files and drops the dependency on global `Zone`, instead allowing it to be provided to each patch as a parameter.

Most of these are pure mechanical transformations. A couple notable files which were somewhat unique:

* `async-test.ts`, `fake-async-test.ts`, and `wtf.ts` had unique IIFE usage and patch `Zone` itself. This removes the IIFE and exports the function instead.
* `jest.ts` and `jasmine.ts` have a unique `jest` global usage which needs to be declared.

PR Close #53443
2024-03-15 18:11:33 -07:00
JiaLiPassion
86372538ab refactor(zone.js): remove zone-async-tagging from zone.js (#47416)
1. Remove `zone-async-tagging` implementation from zone.js and move the
implementation to `@angular/core`, so `@angular/core` can import this
package more easily for better treeshaking.
2. Add `async tagging zone` implemenation into `@angular/core` package.
So we don't need to get the `AsyncStackTaggingZoneSpec` from `global`
instance, we can import the `class` directly for better treeshaking.
3. Only load this ZoneSpec when `ngDevMode` is `true`.

PR Close #47416
2022-09-23 14:44:38 -07:00
Victor Porof
91954cf20e fix(zone.js): Fix ConsoleTask interface typo (#47090)
Signed-off-by: Victor Porof <victorporof@chromium.org>

PR Close #47090
2022-08-09 17:03:21 -07:00
Victor Porof
f23232ff66 feat(zone.js): Update to the simpler Async Stack Tagging v2 API (#46958)
Signed-off-by: Victor Porof <victorporof@chromium.org>

PR Close #46958
2022-08-04 14:25:35 -07:00
Paul Gschwendtner
72c2567847 feat(zone.js): include zone name when sync-test zone reports tasks
The sync-test zone is used in e.g. `describe` to raise an error when
there is asynchronous code scheduled in describe blocks. This commit
includes the zone name in such thrown errors to allow for us to include
the jasmine describe name in the error. This will be wired up in the
jasmine zonejs patches separately.
2022-07-18 19:19:00 +02:00
Paul Gschwendtner
4e0cee52f0 fix(core): do not invoke jasmine done callback multiple times with waitForAsync
Currently tests written using `waitForAsync` would be prone to Jasmine
warnings or errors (depending on the version) for tests incorrectly
invoking asynchronous jasmine `done` callbacks multiple times.

This can happen because the async test zone logic schedules the
`done` callback to be called using `setTimeout`, but this could
be invoked multiple times, causing multiple `done` invocations to
be scheduled. Most of the issues have been resolved with #45025,
but it does not solve the case of multiple tasks finished and callbacks
being scheduled.

Technically, the current logic is built in way that _should_ result in
`_finishCallbackIfDone` and eventually the `done` callback to be invoked
at maximium once. This is unfortunately not the case in some rather
advanced/unexpected scenarios (like our AngularJS upgrade tests) where
the scenario is the following (and microtasks from before the actual
`waitForAsync` spec are still completing -- which is valid):

```
1. A test `beforeEach` schedules a microtask in the ProxyZone.
2. An actual empty `it` spec executes in the AsyncTestZone` (using e.g. `waitForAsync`).
3. The `onInvoke` invokes `_finishCallbackIfDone` because the spec runs synchronously.
4. We wait the scheduled timeout (see below) to account for unhandled promises.
5. The microtask from (1) finishes and `onHasTask` is invoked.

--> We register a second `_finishCallbackIfDone` even though we have scheduled a timeout.
--> we execute the `done` callback twice because the async zone spec state is "stable"
```
2022-07-18 19:19:00 +02:00
JiaLiPassion
848a00956e feat(zone.js): add AsyncStackTaggingZoneSpec implementation (#46693)
Chrome has an experimental API to improve the debug experience of the
async tasks.
The details can be found here https://bugs.chromium.org/p/chromium/issues/detail?id=332624#c29

This commit add the `async stack tagging` support in the `zone.js`.
User can `import 'zone.js/plugins/async-stack-tagging';` to enable this
feature.

PR Close #46693
2022-07-11 20:01:50 +00:00
Krzysztof Platis
f19b36f462 fix(zone.js): in TaskTrackingZoneSpec track a periodic task until it is cancelled (#45391)
Before this change, the macrotask for `setInterval(callback, ms)` was no
longer tracked by `TaskTrackingZoneSpec` after the `callback` was
invoked for the first time. Now the periodic macrotask is tracked until
it is cancelled, e.g. `clearInterval(id)`.

BREAKING CHANGE: in TaskTrackingZoneSpec track a periodic task until it is cancelled

The breaking change is scoped only to the plugin
`zone.js/plugins/task-tracking`. If you used `TaskTrackingZoneSpec` and
checked the pending macroTasks e.g. using `(this.ngZone as any)._inner
._parent._properties.TaskTrackingZone.getTasksFor('macroTask')`, then
its behavior slightly changed for periodic macrotasks. For example,
previously the `setInterval` macrotask was no longer tracked after its
callback was executed for the first time. Now it's tracked until
the task is explicitly cancelled, e.g  with `clearInterval(id)`.

fixes 45350

PR Close #45391
2022-03-24 10:53:36 -07:00
JiaLiPassion
dea7234a76 fix(zone.js): async-test should only call done once (#45025)
`AsyncTestZoneSpec` triggers jasmine `done()` function multiple times
and causes warning

```
An asynchronous function called its 'done' callback more than once. This is a bug in the spec, beforeAll, beforeEach, afterAll, or afterEach function in question. This will be treated as an error in a future version. See<https://jasmine.github.io/tutorials/upgrading_to_Jasmine_4.0#deprecations-due-to-calling-done-multiple-times> for more information
```

The reproduce case will be running some `Zone.run()` inside
`waitForAsync()`.

```
it('multiple done', waitForAsync(() => {
  Zone.current.run(() => {});
  Zone.current.run(() => {});
}));
```

The reason the `done()` is called in the `onInvoke()` hook is to handle
the case that the testBody is totally sync, but we should only do this
check for the entry function not for all `Zone.run()` scenario.

Another issue is if we run nested zone inside `waitForAsync()`, the
`onHasTask()` hook will be triggered multiple times, and cause `done()`
be triggered multiple times, so we need to only trigger the `done()`
when the zone is `AsyncTestZone`.

PR Close #45025
2022-02-09 10:18:56 -08:00
Andrew Scott
fdfcef5a0a build: enable useUnknownInCatchVariables (#44679)
This unblocks the internal migration to turn the option on in g3.

PR Close #44679
2022-02-01 18:17:29 +00:00
Alan Agius
aaf9b31fb4 feat(core): drop support for zone.js 0.10.x (#40823)
With this change we drop support for zone.js 0.10.x.
This is needed because in version 12 the CLI will only work with `~0.11.4`. See angular/angular-cli#20034.

BREAKING CHANGE:

Minimum supported `zone.js` version is `0.11.4`

PR Close #40823
2021-02-24 07:58:29 -08:00
JiaLiPassion
1cba56e11f refactor(core): remove unused fakeAsyncFallback and asyncFallback (#37879)
`zone.js` 0.8.25 introduces `zone-testing` bundle and move all `fakeAsync/async` logic
from `@angular/core/testing` to `zone.js` package. But in case some user still using the old
version of `zone.js`, an old version of `fakeAsync/async` logic were still kept inside `@angular/core/testing`
package as `fallback` logic. Since now `Angular8+` already use `zone.js 0.9+`, so
those fallback logic is removed.

PR Close #37879
2020-11-20 08:34:59 -08:00
JiaLiPassion
c53f19ac47 refactor(zone.js): rename several internal apis in fake async zone spec (#39127)
In `FakeAsyncZoneSpec`, there are several variables and APIs to identify
different times, and the names are confusing, in this commit, they are
renamed for more clear understandings.

1. currentTickTime, the tick millis advanced.
2. getFakeBaseSystemTime(), return the fake base system time.
3. setFakeBaseSystemTime(), set the fake base system time.
4. getRealSystemTime(), get the underlying native system time.

PR Close #39127
2020-10-13 15:56:22 -07:00
JiaLiPassion
82d54fe8c3 feat(zone.js): add jest fakeTimers support (#39016)
Close #38851, support `jest` fakeTimers APIs' integration with `fakeAsync()`.
After enable this feature, calling `jest.useFakeTimers()` will make all test
run into `fakeAsync()` automatically.

```
beforeEach(() => {
    jest.useFakeTimers('modern');
  });
  afterEach(() => {
    jest.useRealTimers();
  });

  test('should run into fakeAsync() automatically', () => {
    const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
    expect(fakeAsyncZoneSpec).toBeTruthy();
  });
```

Also there are mappings between `jest` and `zone` APIs.

- `jest.runAllTicks()` will call `flushMicrotasks()`.
- `jest.runAllTimers()` will call `flush()`.
- `jest.advanceTimersByTime()` will call `tick()`
- `jest.runOnlyPendingTimers()` will call `flushOnlyPendingTimers()`
- `jest.advanceTimersToNextTimer()` will call `tickToNext()`
- `jest.clearAllTimers()` will call `removeAllTimers()`
- `jest.getTimerCount()` will call `getTimerCount()`

PR Close #39016
2020-10-05 13:23:17 -07:00
JiaLiPassion
583a9d38a1 feat(zone.js): upgrade zone.js to angular package format(APF) (#36540)
Close #35157

In the current version of zone.js, zone.js uses it's own package format, and it is not following the rule
of Angualr package format(APF), so it is not easily to be consumed by Angular CLI or other bundle tools.
For example, zone.js npm package has two bundles,

1. zone.js/dist/zone.js, this is a `es5` bundle.
2. zone.js/dist/zone-evergreen.js, this is a `es2015` bundle.

And Angular CLI has to add some hard-coding code to handle this case, o5376a8b139/packages/schematics/angular/application/files/src/polyfills.ts.template (L55-L58)

This PR upgrade zone.js npm package format to follow APF rule, https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/edit#heading=h.k0mh3o8u5hx

The updated points are:

1. in package.json, update all bundle related properties

```
  "main": "./bundles/zone.umd.js",
  "module": "./fesm2015/zone.js",
  "es2015": "./fesm2015/zone.js",
  "fesm2015": "./fesm2015/zone.js",
```

2. re-organize dist folder, for example for `zone.js` bundle, now we have

```
  dist/
      bundles/
             zone.js            // this is the es5 bundle
      fesm2015/
             zone.js            // this is the es2015 bundle (in the old version is `zone-evergreen.js`)
```

3. have several sub-packages.

1. `zone-testing`, provide zone-testing bundles include zone.js and testing libraries
2. `zone-node`, provide zone.js implemention for NodeJS
3. `zone-mix`, provide zone.js patches for both Browser and NodeJS

All those sub-packages will have their own `package.json` and the bundle will reference `bundles(es5)` and `fesm2015(es2015)`.

4. keep backward compatibility, still keep the `zone.js/dist` folder, and all bundles will be redirected to `zone.js/bundles` or `zone.js/fesm2015` folders.

PR Close #36540
2020-06-11 11:08:48 -07:00
Joey Perrott
d1ea1f4c7f build: update license headers to reference Google LLC (#37205)
Update the license headers throughout the repository to reference Google LLC
rather than Google Inc, for the required license headers.

PR Close #37205
2020-05-26 14:26:58 -04:00
Joey Perrott
698b0288be build: reformat repo to new clang@1.4.0 (#36613)
PR Close #36613
2020-04-14 12:08:36 -07:00
JiaLiPassion
55b3f97be0 fix(zone.js): tickOptions's processNewMacroTasksSynchronously should default to true when flag omitted (#35814)
Calling `tick(0, null)` defaults `processNewMacroTasksSynchronously` flag to `true`, however calling  `tick(0, null, {})` defaults `processNewMacroTasksSynchronously` to `undefined`. This is undesirable behavior since unless the flag is set explicitly it should still default to `true`.

PR Close #35814
2020-03-06 17:33:57 -05:00
JiaLiPassion
17b862cf82 feat: add an tickOptions parameter with property processNewMacroTasksSynchronously. (#33838)
This option will control whether to invoke the new macro tasks when ticking.

Close #33799

PR Close #33838
2020-02-20 15:14:59 -08:00
Martin Probst
09536423e8 fix(zone.js): work around TS3.7 issue (#33294)
In TypeScript 3.7, circularity detection misfires on the declaration of `value` here.
https://github.com/microsoft/TypeScript/issues/32950

Declaring an explicit type avoids the problem.

PR Close #33294
2019-11-01 17:46:03 +00:00
Alex Eagle
5c9a8961da fix(zone.js): don't rely on global node typings outside of node/ directory (#31783)
PR Close #31783
2019-07-30 12:59:40 -07:00
Paul Gschwendtner
60f58bf051 refactor: ensure zone.js can be built with typescript strict flag (#30993)
As part of FW-1265, the `zone.js` package is made compatible
with the TypeScript `--strict` flag. Read more about the strict flag [here](https://www.typescriptlang.org/docs/handbook/compiler-options.html)

PR Close #30993
2019-07-18 14:21:26 -07:00
Alex Eagle
e6f1b04cd5 fix(zone.js): restore definition of global (#31453)
This partially reverts some changes from 71b9371180 (diff-dd469785fca8680a5b33b1e81c5cfd91R1420)
These broke the g3sync of zone.js because we use the output of the TypeScript compiler directly, rather than rely on the rollup commonjs plugin to define the global symbol

PR Close #31453
2019-07-09 09:34:50 -07:00
Michael Prentice
95a9d67599 test(zone.js): fix typos (#31358)
Relates to #31144

PR Close #31358
2019-07-02 11:29:33 -07:00
JiaLiPassion
5eb7426216 build: move zone.js to angular repo (#30962)
PR Close #30962
2019-06-20 11:27:39 -07:00