Angular2 Inject ElementRef在单元测试中

Mat*_*Nls 21 unit-testing dependency-injection angularjs-e2e angular

我正在尝试测试通过DI接收对ElementRef的引用的组件.

import { Component, OnInit, ElementRef } from '@angular/core';

@Component({
  selector: 'cp',
  templateUrl: '...',
  styleUrls: ['...']
})
export class MyComponent implements OnInit {

  constructor(private elementRef: ElementRef) {
    //stuffs
  }

  ngAfterViewInit() {
    // things
  }

  ngOnInit() {
  }
}
Run Code Online (Sandbox Code Playgroud)

和测试:

import {
  beforeEach,
  beforeEachProviders,
  describe,
  expect,
  it,
  inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component, Renderer, ElementRef } from '@angular/core';
import { By } from '@angular/platform-browser';

describe('Component: My', () => {
  let builder: TestComponentBuilder;

  beforeEachProviders(() => [MyComponent]);
  beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
    builder = tcb;
  }));

  it('should inject the component', inject([MyComponent],
      (component: MyComponent) => {
    expect(component).toBeTruthy();
  }));

  it('should create the component', inject([], () => {
    return builder.createAsync(MyComponentTestController)
      .then((fixture: ComponentFixture<any>) => {
        let query = fixture.debugElement.query(By.directive(MyComponent));
        expect(query).toBeTruthy();
        expect(query.componentInstance).toBeTruthy();
      });
  }));
});

@Component({
  selector: 'test',
  template: `
    <cp></cp>
  `,
  directives: [MyComponent]
})
class MyTestController {
}
Run Code Online (Sandbox Code Playgroud)

组件和测试蓝图都是由Angular-cli生成的.现在,我无法弄清楚我应该添加哪个提供程序,beforeEachProviders以便注入ElementRef才能成功.当我跑步时,ng test我得到了Error: No provider for ElementRef! (MyComponent -> ElementRef).

Nor*_*ern 27

Can't resolve all parameters for ElementRef: (?)在角度2.4中使用来自@ gilad-s的模拟遇到Error

将mock类修改为:

export class MockElementRef extends ElementRef {
  constructor() { super(null); }
}
Run Code Online (Sandbox Code Playgroud)

解决了测试错误.

从角度源代码中读取:https: //github.com/angular/angular/blob/master/packages/core/testing/src/component_fixture.ts#L17-L60 fixture的elementRef不是从mock创建的注射.在正常开发中,我们ElementRef在注入组件时没有明确提供.我认为TestBed应该允许相同的行为.


小智 12

在Angular 2.2.3上:

export class MockElementRef extends ElementRef {}
Run Code Online (Sandbox Code Playgroud)

然后在测试中:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    providers: [
      //more providers
      { provide: ElementRef, useClass: MockElementRef }
    ]
  }).compileComponents();
}));
Run Code Online (Sandbox Code Playgroud)

  • 使用Angular 5,我还需要将属性`nativeElement`添加到`MockElementRef`中:`class MockElementRef扩展了ElementRef {nativeElement = {}; }` (3认同)

Mat*_*Nls 8

要注入ElementRef:

  1. 创建一个模拟
class MockElementRef implements ElementRef {
  nativeElement = {};
}
Run Code Online (Sandbox Code Playgroud)
  1. 将模拟提供给被测组件
beforeEachProviders(() => [Component, provide(ElementRef, { useValue: new MockElementRef() })]);
Run Code Online (Sandbox Code Playgroud)

编辑:这是在rc4上工作.最终版本引入了重大更改并使此答案无效.