我正在尝试测试通过 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/