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

1

0

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?

Diarmit answered 6/9, 2019 at 7:32 Comment(3)
Quick question, but is MyService correctly annotated with @Injectable ?Macgregor
Can you please check import of IMyService. Are you importing from right path ?Tacita
(1) MockMyService is annotated with @Injectable, that's the service I want to use (2) I do try to import IMyService but as it's referred to as a string in the unit test it doesn't appear as used in the imports (i.e., it's a different colour) NB. The actual component works, it's the unit test that doesn'tDiarmit
D
0

I think I've found an answer

https://mcmap.net/q/747603/-can-39-t-resolve-all-parameters-for-appcomponent

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

Diarmit answered 6/9, 2019 at 8:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.