James Crinkley
James Crinkley

Reputation: 1408

Angular2 Component test - Error: Can't resolve all parameters

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!

Upvotes: 5

Views: 7797

Answers (1)

PaTT
PaTT

Reputation: 126

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) {}

Upvotes: 5

Related Questions