Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 911
James Crinkley Avatar asked Jan 26 '17 22:01

James Crinkley


1 Answers

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) {}
like image 172
PaTT Avatar answered Sep 27 '22 22:09

PaTT