Search code examples
angularangular-unit-test

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


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?


Solution

  • 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