Skip to content

Commit 5de7575

Browse files
AndrewKushnirthePunderWoman
authored andcommitted
fix(core): reset cached scope for components that were overridden using TestBed (#52916)
Currently, when a component is overriden using `TestBed.overrideComponent`, Angular retains calculated scope for that component (a set of components and directives used within a component). This may cause stale information to be used in tests in some cases. This commit updates the logic to reset overridden component scope, so it gets re-computed during the next invocation. Resolves #52817. PR Close #52916
1 parent a523801 commit 5de7575

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

packages/core/test/test_bed_spec.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,56 @@ describe('TestBed with Standalone types', () => {
175175
TestBed.resetTestingModule();
176176
});
177177

178+
it('should override dependencies of standalone components', () => {
179+
@Component({
180+
selector: 'dep',
181+
standalone: true,
182+
template: 'main dep',
183+
})
184+
class MainDep {
185+
}
186+
187+
@Component({
188+
selector: 'dep',
189+
standalone: true,
190+
template: 'mock dep',
191+
})
192+
class MockDep {
193+
}
194+
195+
@Component({
196+
selector: 'app-root',
197+
standalone: true,
198+
imports: [MainDep],
199+
template: '<dep />',
200+
})
201+
class AppComponent {
202+
}
203+
204+
TestBed.configureTestingModule({imports: [AppComponent]});
205+
206+
let fixture = TestBed.createComponent(AppComponent);
207+
fixture.detectChanges();
208+
209+
// No overrides defined, expecting main dependency to be used.
210+
expect(fixture.nativeElement.innerHTML).toBe('<dep>main dep</dep>');
211+
212+
// Emulate an end of a test.
213+
TestBed.resetTestingModule();
214+
215+
// Emulate the start of a next test, make sure previous overrides
216+
// are not persisted across tests.
217+
TestBed.configureTestingModule({imports: [AppComponent]});
218+
TestBed.overrideComponent(AppComponent, {set: {imports: [MockDep]}});
219+
220+
fixture = TestBed.createComponent(AppComponent);
221+
fixture.detectChanges();
222+
223+
// Main dependency was overridden, expect to see a mock.
224+
expect(fixture.nativeElement.innerHTML).toBe('<dep>mock dep</dep>');
225+
});
226+
227+
178228
it('should override providers on standalone component itself', () => {
179229
const A = new InjectionToken('A');
180230

packages/core/testing/src/test_bed_compiler.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,9 @@ export class TestBedCompiler {
396396
}
397397

398398
this.maybeStoreNgDef(NG_COMP_DEF, declaration);
399+
if (USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
400+
depsTracker.clearScopeCacheFor(declaration);
401+
}
399402
compileComponent(declaration, metadata);
400403
});
401404
this.pendingComponents.clear();

0 commit comments

Comments
 (0)