Angular 4: Mock ElementRef : <p>I'm trying to figure out how to mock an <code>ElementRef</code> that is injected into a component. My component is as follows:</p>

<p><strong>app.component.ts:</strong></p>

<pre><code>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);
  }
}
</code></pre>

<p>and my test spec as follows:</p>

<p><strong>app.component.spec.ts:</strong></p>

<pre><code>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', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers: [
        {provide: ElementRef, useClass: MockElementRef},
        {provide: AppService, useClass: MockAppService}
      ]
    }).compileComponents();
  }));

  ...
});
</code></pre>

<p>When the tests are ran, the output from the <code>console.log</code>'s in constructor of <code>app.component.ts</code> is:</p>

<p><a href="https://i.stack.imgur.com/63m25.png" rel="noreferrer"><img src="https://i.stack.imgur.com/63m25.png" alt="console output"></a></p>

<p>As you can see, it's injecting the <code>MockAppService</code> but not the <code>MockElementRef</code> (even though they are both mocked in the same way).</p>

<p>This <a href="https://stackoverflow.com/questions/38623065/angular2-inject-elementref-in-unit-test">SO post suggests</a> 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?</p>

<p>A Plunker with the above code and Jasmine tests can be found <a href="https://plnkr.co/edit/gTjUg396RI2SmSvGWjKd?p=preview" rel="noreferrer">here</a>. 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.</p>
