Yur*_*aki 5 unit-testing jasmine typescript angular
我有一个带有输入的组件fsElement
。这fsElement
应该是任何 html 元素的 id。然后我的组件使用这个提供的 id 来获取元素的高度。这是相关代码:
export class BotaoTelaCheiaComponent implements OnInit {
@Input() fsElement:string;
private _originalHeight: number;
constructor() { }
ngOnInit() {}
ngAfterViewInit() {
this._originalHeight = document.getElementById(this.fsElement).clientHeight;
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行时 ng test
它失败了TypeError: Cannot read property 'clientHeight' of null
。我只是运行 Angular cli 生成的标准测试:
describe('BotaoTelaCheiaComponent', () => {
let component: BotaoTelaCheiaComponent;
let fixture: ComponentFixture<BotaoTelaCheiaComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BotaoTelaCheiaComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BotaoTelaCheiaComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
如何重写此测试或我的组件以使其通过?
生命周期挂钩(OnInit
等)在 中执行的首次更改检测时触发beforeEach
。
为了避免这种情况,fixture.detectChanges()
应该按需删除beforeEach
并调用。
it('should create', () => {
expect(component).toBeTruthy();
component.fsElement = 'foo';
spyOn(document, 'getElementById').and.returnValue({ clientHeight: 100 });
fixture.detectChanges();
expect(document.getElementById).toHaveBeenCalledWith('foo');
expect(component['_originalHeight']).toBe(100);
});
Run Code Online (Sandbox Code Playgroud)
或者,可以将真实的 DOM 元素id="foo"
添加到 DOM in 中beforeEach
并在 中删除afterEach
。
直接 DOM 访问使 Angular 测试变得复杂,因为它需要模拟全局变量或 DOM。
归档时间: |
|
查看次数: |
6161 次 |
最近记录: |