[英]Angular2 Inject ElementRef in unit test
I am trying to test a component that receives a reference to ElementRef through DI.我正在尝试测试通过 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() {
}
}
and the test:和测试:
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 {
}
Both the component and the test blueprint have been generated by Angular-cli.组件和测试蓝图均由 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.现在,我不知道应该在
beforeEachProviders
添加哪个提供程序(如果有)才能成功注入 ElementRef。 When I run ng test
I got Error: No provider for ElementRef! (MyComponent -> ElementRef)
当我运行
ng test
出现Error: No provider for ElementRef! (MyComponent -> ElementRef)
Error: No provider for ElementRef! (MyComponent -> ElementRef)
. Error: No provider for ElementRef! (MyComponent -> ElementRef)
。
I encounter Can't resolve all parameters for ElementRef: (?)
Error using the mock from @gilad-s in angular 2.4我遇到
Can't resolve all parameters for ElementRef: (?)
Error using the mock from @gilad-s in angular 2.4
Modified the mock class to:将模拟类修改为:
export class MockElementRef extends ElementRef {
constructor() { super(null); }
}
resolves the test error.解决了测试错误。
Reading from the angular source code here: https://github.com/angular/angular/blob/master/packages/core/testing/src/component_fixture.ts#L17-L60 the elementRef of the fixture is not created from the mock injection.从这里的角度源代码读取: https ://github.com/angular/angular/blob/master/packages/core/testing/src/component_fixture.ts#L17-L60 夹具的 elementRef 不是从模拟创建的注射。 And in normal development, we do not explicitly provide
ElementRef
when injecting to a component.并且在正常开发中,我们在注入组件时不会显式提供
ElementRef
。 I think TestBed
should allow the same behaviour.我认为
TestBed
应该允许相同的行为。
On Angular 2.2.3:在 Angular 2.2.3 上:
export class MockElementRef extends ElementRef {}
Then in the test:然后在测试中:
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
//more providers
{ provide: ElementRef, useClass: MockElementRef }
]
}).compileComponents();
}));
To inject an ElementRef:要注入 ElementRef:
class MockElementRef implements ElementRef {
nativeElement = {};
}
beforeEachProviders(() => [Component, provide(ElementRef, { useValue: new MockElementRef() })]);
EDIT: This was working on rc4.编辑:这是在 rc4 上工作的。 Final release introduced breaking changes and invalidates this answer.
最终版本引入了重大更改并使此答案无效。
A good way is to use spyOn
and spyOnProperty
to instant mock the methods and properties as needed.一个好方法是使用
spyOn
和spyOnProperty
根据需要即时模拟方法和属性。 spyOnProperty
expects 3 properties and you need to pass get
or set
as third property. spyOnProperty
需要 3 个属性,您需要将get
或set
作为第三个属性传递。 spyOn
works with class and method and returns required value. spyOn
与类和方法spyOn
工作并返回所需的值。
const div = fixture.debugElement.query(By.css('.ellipsis-overflow'));
// now mock properties
spyOnProperty(div.nativeElement, 'clientWidth', 'get').and.returnValue(1400);
spyOnProperty(div.nativeElement, 'scrollWidth', 'get').and.returnValue(2400);
Here I am setting the get
of clientWidth
of div.nativeElement
object.在这里我设置
get
的clientWidth
的div.nativeElement
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.