Angular,对通过接口创建服务的组件进行单元测试

Angular, unit testing a component that creates a service via an interface

鉴于此组件在本地创建服务

@Component({
    <removed for clarity>
    providers: [
        { provide: 'IMyService', useClass: MyService },
    ]
})
export class MyComponent implements OnInit, OnDestroy, AfterViewInit
{
    constructor(private data: IMyService){}
}

我一直在尝试在单元测试中提供服务,类似这样

beforeEach(async(() =>
{
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [
            { provide: 'IMyService', useClass: MockMyService },
        ]
    })
    /*
        .overrideProvider('IMyService', { useValue: MockMyService })
        .overrideComponent(MyComponent, {
        set: {
            providers: [
                { provide: 'IMyService', useClass: MockMyService }
            ]
        }
    })
   */
.compileComponents();

注释掉的部分是我尝试过的。

但我经常收到这条消息

Failed: Can't resolve all parameters for MyComponent: (?)

我在这里错过了什么?

我想我找到了答案

constructor(
@Inject('IMyService') private data: IMyService,

正如评论所说,"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"

此外,您只需要在单元测试中使用 overrideProvider,但对于在组件范围内创建的提供程序确实需要它