Reputation: 3612
I'm trying to unit test my component but the basic test fails.
cannot resolve all parameters for MyComponent(?.)
I tried adding forwardRef() in my component's constructor it works though. But i do not want to use it just because of test failure and it is not recommended.
please ignore if there are any typo. i've added the code snippet. sorry that i cannot add the actual code here.
src
./services
my-service-c.ts
import { MyServiceQ } from './my-service-q';
...
@Injectable()
export class MyServiceC {
constructor(private myServiceQ: MyServiceQ) { }
...
getMyServiceQ(){
return this.myServiceQ;
}
}
./components
my-component.ts
import { MyServiceC } from '../services/my-service-c';
@Component() {...}
export class MyComponent {
private myServiceQ;
constructor(private myServiceC: MyServiceC) {
this.myServiceQ = this.myServiceC.getMyServiceQ();
}
}
my-component.spec.ts
import { MyServiceC } from '../services/my-service-c';
import { MockMyServiceC } from '../fixtures/mock-my-service-c';
import { MyComponent } from './my-component';
..other imports...
beforeEach( () => {
TestBed.configureTestingModule({
providers: [
{ provide: MyServiceC, useClass: MockMyServiceC }
],
declarations: [ MyComponent ]
});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be defined',
() => expect(component).toBeDefined();
);
Please let me know if you have suggestions. I've been trying to find a solution for a long time. Thanks in advance..
Upvotes: 0
Views: 669
Reputation: 8165
You stated in your comment that "i've two mock service (MockMyServiceC injects MockMyServiceQ) same as the actual service."
At the moment you inject MockMyServiceC
in your test all dependencies of MockMyServiceC
have to be resolved as well, but you didn't provide them.
Changing your test a bit should solve your problem:
TestBed.configureTestingModule({
providers: [
MockMyServiceQ,
{ provide: MyServiceC, useClass: MockMyServiceC }
],
declarations: [ MyComponent ]
});
A hint: This can quickly become hard to maintain. Your mocked services should always inject the same, real services. Then you could just provide them like this:
TestBed.configureTestingModule({
providers: [
{ provide: MyServiceQ, useClass: MockMyServiceQ },
{ provide: MyServiceC, useClass: MockMyServiceC }
],
declarations: [ MyComponent ]
});
Otherwise you come to a point where you are injecting MockServices directly as well as provide them via useClass
. Think about what happens for your test if your component injects MyServiceQ as well.
Upvotes: 1