unit-testing - Angular2 在单元测试中注入(inject) ElementRef

标签 unit-testing angular dependency-injection angularjs-e2e

我正在尝试测试通过 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() {
  }
}

和测试:

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 {
}

组件和测试蓝图均由 Angular-cli 生成。现在,我不知道应该在 beforeEachProviders 中添加哪个提供程序(如果有的话)以便成功注入(inject) ElementRef。当我运行 ng test 时,我得到了 Error: No provider for ElementRef! (MyComponent -> ElementRef)

最佳答案

我遇到 Can't resolve all parameters for ElementRef: (?) Error using the mock from @gilad-s in angular 2.4

将模拟类修改为:

export class MockElementRef extends ElementRef {
  constructor() { super(null); }
}

解决测试错误。

在此处阅读 Angular 源代码:https://github.com/angular/angular/blob/master/packages/core/testing/src/component_fixture.ts#L17-L60 夹具的 elementRef 不是从模拟注入(inject)创建的。并且在正常开发中,我们在向组件注入(inject)时不会显式提供 ElementRef。我认为 TestBed 应该允许相同的行为。

关于unit-testing - Angular2 在单元测试中注入(inject) ElementRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38623065/

相关文章:

Angular 管 : Convert string into Json and get member value

performance - Angular 性能 : component exposes public object with 500+ (sub-) members

java - 使用构造函数注入(inject)模拟 Spring 类

javascript - Angular 4 - 如果 ngModel 不为空则添加类

c# - MVVM 中的依赖注入(inject)和单一职责原则

c# - 由于循环作用域回调引用导致 ninject 内存泄漏

java - Dagger组件依赖含义

unit-testing - JUnit 4 基本功能

iphone - 为 mac 单元测试运行谷歌工具包时出错

maven - Kotlin-Maven不执行测试