问题
Does TestBed.overrideModule replace previously added providers?
I have a Component c1 which uses a dynamically created component c2. I read that I need to use overrideModule to add entryComponents entry in the TestBed.
So I did this
TestBed.configureTestingModule({
declarations: [ NewPracticeQuestionComponent,
DialogBoxComponent,
ShowErrorsComponent],
imports:[ReactiveFormsModule,HttpClientTestingModule],
providers:[WebToBackendInterfaceService,
HelperService,
AuthService,
{provide:QuestionManagementService, useClass:MockQuestionManagementService}] //NOTE I HAVE A DIFFERENT PROVIDER HERE
});
TestBed.overrideModule(BrowserDynamicTestingModule, {
set: {
entryComponents: [DialogBoxComponent]/*DialogBoxComponent is created dynamically (imperatively), soit nee to be ddded in entryComponent*/
}
});
TestBed.compileComponents();
Above, I have provided MockQuestionManagementService as different provider for QuestionManagementService. But I notice that when creating the component, Angular created QuestionManagementService!!
to fix the problem, I had to explicitly call TestBed.overrideProvider
TestBed.configureTestingModule({
declarations: [ NewPracticeQuestionComponent,
DialogBoxComponent,
ShowErrorsComponent],
imports:[ReactiveFormsModule,HttpClientTestingModule],
providers:[WebToBackendInterfaceService,
HelperService,
AuthService,
{provide:QuestionManagementService, useClass:MockQuestionManagementService}]
});
TestBed.overrideModule(BrowserDynamicTestingModule, {
set: {
entryComponents: [DialogBoxComponent]/*DialogBoxComponent is created dynamically (imperatively), soit nee to be ddded in entryComponent*/
}
});
TestBed.overrideProvider(QuestionManagementService,{useValue: new MockQuestionManagementService},); //THIS ADDED EXPLICITLY
TestBed.compileComponents();
}));
Now Angular added the MockQuestionManagementService. Did I incorrectly use overrideModule or it is expected behaviour of TestBed.overrideModule?
回答1:
The issue was not with TestBed but with the way I had configured the providers. I had used @Injectable({ providedIn: 'root'}) in the service's .ts file rather than in module's .ts. So even if I configured the TestModule to use the provided configuration ({provide:QuestionManagementService, useClass:MockQuestionManagementService}), it seems it kept picking the instance of QuestionManagementService from the root injector unless I explicitly override it by calling TestBed.overrideProvider(QuestionManagementService,{useValue: new MockQuestionManagementService},);
Though I still wonder why the configuration provided to the TestBed didn't work. Isn't the lookup for dependencies from Component to Module to Root?
来源:https://stackoverflow.com/questions/54135268/testbed-overridemodule-method-seem-to-remove-previously-added-providers