Skip to content

Commit 674cf37

Browse files
committed
fix(cdk/testing): fix behavior in fakeAsync tests
1 parent e58153e commit 674cf37

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/cdk/testing/testbed/testbed-harness-environment.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,22 @@ function uninstallAutoChangeDetectionStatusHandler(fixture: ComponentFixture<unk
6767
}
6868
}
6969

70+
/** Whether we are currently in the fake async zone. */
71+
function isInFakeAsyncZone() {
72+
return Zone?.current.get('FakeAsyncTestZoneSpec') != null;
73+
}
74+
7075
/**
7176
* Triggers change detection for a specific fixture.
7277
* @param fixture The fixture to trigger change detection for.
7378
*/
7479
async function detectChanges(fixture: ComponentFixture<unknown>) {
7580
fixture.detectChanges();
76-
await fixture.whenStable();
81+
if (isInFakeAsyncZone()) {
82+
flush();
83+
} else {
84+
await fixture.whenStable();
85+
}
7786
}
7887

7988
/** A `HarnessEnvironment` implementation for Angular's Testbed. */
@@ -153,7 +162,7 @@ export class TestbedHarnessEnvironment extends HarnessEnvironment<Element> {
153162
// cannot just rely on the task state observable to become stable because the state will
154163
// never change. This is because the task queue will be only drained if the fake async
155164
// zone is being flushed.
156-
if (Zone!.current.get('FakeAsyncTestZoneSpec')) {
165+
if (isInFakeAsyncZone()) {
157166
flush();
158167
}
159168

src/cdk/testing/tests/testbed.spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,13 @@ describe('TestbedHarnessEnvironment', () => {
8383
const element = TestbedHarnessEnvironment.getNativeElement(await harness.host());
8484
expect(element.id).toContain('root');
8585
});
86+
87+
it('should wait for async operation to complete in fakeAsync test', fakeAsync(async () => {
88+
const asyncCounter = await harness.asyncCounter();
89+
expect(await asyncCounter.text()).toBe('5');
90+
await harness.increaseCounter(3);
91+
expect(await asyncCounter.text()).toBe('8');
92+
}));
8693
});
8794

8895
describe('change detection behavior', () => {

0 commit comments

Comments
 (0)