问题
Given this component that creates a service locally
@Component({
<removed for clarity>
providers: [
{ provide: 'IMyService', useClass: MyService },
]
})
export class MyComponent implements OnInit, OnDestroy, AfterViewInit
{
constructor(private data: IMyService){}
}
I've been trying to supply the service in the unit test, something like this
beforeEach(async(() =>
{
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
{ provide: 'IMyService', useClass: MockMyService },
]
})
/*
.overrideProvider('IMyService', { useValue: MockMyService })
.overrideComponent(MyComponent, {
set: {
providers: [
{ provide: 'IMyService', useClass: MockMyService }
]
}
})
*/
.compileComponents();
The commented out bits being things I've tried.
But I constantly get this message
Failed: Can't resolve all parameters for MyComponent: (?)
What am I missing here?
回答1:
I think I've found an answer
https://stackoverflow.com/a/47451244/220545
constructor(
@Inject('IMyService') private data: IMyService,
As the comment says, "This works for me. Without Inject, the app is working fine. However, with ng test, it seems Inject is required. I am using Angular 6"
In addition, you only need overrideProvider in the unit test, but you do need it for providers that are created in the component scope
来源:https://stackoverflow.com/questions/57817610/angular-unit-testing-a-component-that-creates-a-service-via-an-interface