I'm working on testing one of my components for the first time using Karma/Jasmine etc and have been mostly following along with the docs on testing. My component requires 3 constructor arguments;
constructor(
private myService: MyService,
private renderer: Renderer,
private element: ElementRef
) { }
I have attempted to mock/stub those dependencies based on this section of the docs as follows;
// Mocks/Stubs
const myServiceStub = {};
class MockElementRef {}
class MockRenderer {}
// beforeEach block
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: [
{ provide: ElementRef, useClass: MockElementRef },
{ provide: Renderer, useClass: MockRenderer },
{ provide: MyService, useValue: myServiceStub},
]
});
fixture = TestBed.createComponent(MyComponent);
});
Despite this, whenever I run my tests I get the following error;
Error: Can't resolve all parameters for MyComponent: (?, ?, ?).
at SyntaxError.ZoneAwareError (test.ts:9250:33)
at SyntaxError.BaseError [as constructor] (test.ts:44243:16)
at new SyntaxError (test.ts:44453:16)
at CompileMetadataResolver._getDependenciesMetadata (test.ts:61503:31)
What am I missing here? Thank you!
It can be caused by circular DI, try to refactor your component MyComponent to inject service like this:
constructor(@Inject(forwardRef(() => MyComponentService)) private myService: MyComponentService) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With