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?

DaggeJ
  • 2,094
  • 1
  • 10
  • 22
tony
  • 2,178
  • 2
  • 23
  • 40
  • Quick question, but is MyService correctly annotated with @Injectable ? – RoadEx Sep 06 '19 at 07:36
  • Can you please check import of `IMyService`. Are you importing from right path ? – Sourav Golui Sep 06 '19 at 07:43
  • (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't – tony Sep 06 '19 at 07:47

1 Answers1

0

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

tony
  • 2,178
  • 2
  • 23
  • 40