Angular2 Inject ElementRef in unit test
I encounter Can't resolve all parameters for ElementRef: (?)
Error using the mock from @gilad-s in angular 2.4
Modified the mock class to:
export class MockElementRef extends ElementRef { constructor() { super(null); }}
resolves the test error.
Reading from the angular source code here: https://github.com/angular/angular/blob/master/packages/core/testing/src/component_fixture.ts#L17-L60the elementRef of the fixture is not created from the mock injection. And in normal development, we do not explicitly provide ElementRef
when injecting to a component. I think TestBed
should allow the same behaviour.
On Angular 2.2.3:
export class MockElementRef extends ElementRef {}
Then in the test:
beforeEach(async(() => { TestBed.configureTestingModule({ providers: [ //more providers { provide: ElementRef, useClass: MockElementRef } ] }).compileComponents();}));
To inject an ElementRef:
- Create a mock
class MockElementRef implements ElementRef { nativeElement = {};}
- Provide the mock to the component under test
beforeEachProviders(() => [Component, provide(ElementRef, { useValue: new MockElementRef() })]);
EDIT: This was working on rc4. Final release introduced breaking changes and invalidates this answer.