Angular2在单元测试中注入ElementRef [英] Angular2 Inject ElementRef in unit test
本文介绍了Angular2在单元测试中注入ElementRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试测试通过DI接收对ElementRef的引用的组件.
I am trying to test a component that receives a reference to ElementRef through DI.
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
以便成功注入ElementRef.当我运行ng test
时,我得到了Error: No provider for ElementRef! (MyComponent -> ElementRef)
.
Both the component and the test blueprint have been generated by Angular-cli. Now, I can't figure out which provider, if any, I should add in the beforeEachProviders
for the injection of ElementRef to be successful. When I run ng test
I got Error: No provider for ElementRef! (MyComponent -> ElementRef)
.
推荐答案
在Angular 2.2.3上:
On Angular 2.2.3:
export class MockElementRef extends ElementRef {}
然后在测试中:
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
//more providers
{ provide: ElementRef, useClass: MockElementRef }
]
}).compileComponents();
}));
这篇关于Angular2在单元测试中注入ElementRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文