Angular 4: Mock ElementRef

I am trying to understand how to mock ElementRefthat which 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:

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 tests are run, the constructor output console.login app.component.ts:

console output

As you can see, he introduces MockAppService, but not MockElementRef(although they both mock in the same way).

This SO post offers to customize it like any other layout, however, I noticed that this is for Angular 2 - is it so interesting if things have changed in Angular 4?

. Plunker, "Run Unit Tests", . /Firebug.

+4

Source: https://habr.com/ru/post/1690981/


All Articles