I'm trying to figure out how to mock an ElementRef
that is injected into a component. My component is as follows:
app.component.ts:
import { Component, ElementRef } from '@angular/core';
import { AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app/app.component.html',
styleUrls: ['./app/app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor(private _elementRef: ElementRef, private _appService: AppService) {
console.log(this._elementRef);
console.log(this._appService);
}
}
and my test spec as follows:
app.component.spec.ts:
import { TestBed, async } from '@angular/core/testing';
import { ElementRef, Injectable } from '@angular/core';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
@Injectable()
export class MockElementRef {
nativeElement: {}
}
@Injectable()
export class MockAppService {
}
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
providers: [
{provide: ElementRef, useClass: MockElementRef},
{provide: AppService, useClass: MockAppService}
]
}).compileComponents();
}));
...
});
When the tests are ran, the output from the console.log
's in constructor of app.component.ts
is:
As you can see, it's injecting the MockAppService
but not the MockElementRef
(even though they are both mocked in the same way).
This SO post suggests to set it up as you would any other mock, however I've noticed that this is for Angular 2 - so am wondering if things have changed in Angular 4?
A Plunker with the above code and Jasmine tests can be found here. Run the Plunker then click the "Run Unit Tests" link in order to start the unit tests. The console output can be observed in developer tools/Firebug.