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

喜你入骨 提交于 2019-12-13 04:36:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!