问题
When using the following configuration for a test fixture, I get complaints that the tag cannot be found. Substituting the MockSelectionToolComponent
directly in AppModule
works fine, so must be something else...
// Add the imported module to the imports array in beforeEach
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MockSelectionToolComponent],
imports: [
AppModule
]
}).overrideModule(AppModule, {
remove: {
declarations: [SelectionToolComponent]
}
}).compileComponents();
fixture = TestBed.createComponent(MappingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.initialiseMap();
});
Error: Template parse errors: 'app-selection-tool' is not a known element:
回答1:
So in fact we don't add it to the test module's declaration, but to the original Module:
// Add the imported module to the imports array in beforeEach
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [],
imports: [
AppModule
]
}).overrideModule(AppModule, {
remove: {
declarations: [SelectionToolComponent]
},
add: {
declarations: [MockSelectionToolComponent]
}
}).compileComponents();
fixture = TestBed.createComponent(MappingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.initialiseMap();
});
Good luck finding that documented anywhere.
回答2:
As you stated, it's not possible to directly declare the overrides, but do it in a chained overriding Method. You can also use the set syntax, in component here for example, applies also for module.
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [MockProductCardComponent, ProductListComponent]
})
.overrideComponent(ProductListComponent, {
set: {
providers: [
{ provide: ActivatedRoute, useValue: { fragment: Observable.of(fragment) }},
{ provide: PageScrollService, useClass: MockPageScrollService }
]
}
})
来源:https://stackoverflow.com/questions/44758067/angular-testbed-overridemodule-not-working