【发布时间】:2019-12-13 14:39:52
【问题描述】:
添加 ngAfterViewChecked 后,我的一些 karma jasmine 单元测试失败。我不确定我在这里做错了什么。我尝试初始化下面的“mySwitchEl”,但仍然出现同样的错误。
@Component({
selector: 'my-component',
templateUrl: './my.component.html'
})
export class MyComponent implements OnInit, OnDestroy, AfterViewChecked {
@ViewChild('myswitch') mySwitchEl: ElementRef;
public somethingEnabled: boolean;
public switchWidth: number;
constructor(private cd: ChangeDetectorRef) {
}
ngOnInit(): void {
// do stuff
}
ngOnDestory(): void {
// do stuff
}
ngAfterViewChecked(): void {
this.switchWidth = this.mySwitchEl.nativeElement.offsetWidth * 2;
this.cd.detectChanges();
}
}
这里是单元测试。如果我将“fixture.detectChanges”放在 beforeEach 中,我的所有单元测试都会失败,而不仅仅是少数。
import { Component, ViewChild, ElementRef, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild('myswitch') mySwitchEl: ElementRef;
public somethingEnabled: boolean;
public switchWidth: number;
constructor(private cd: ChangeDetectorRef) {
}
ngOnInit(): void {
// do stuff
}
ngOnDestory(): void {
// do stuff
}
ngAfterViewChecked(): void {
this.switchWidth = this.mySwitchEl.nativeElement.offsetWidth * 2;
this.cd.detectChanges();
}
}
html 示例
<label class="switch-light" [style.width.px]="switchWidth">
<a class="btn btn-primary" id="my-switch-identifier" #myswitch>
Some Text Here
</a>
</label>
我在这里做错了什么?
【问题讨论】:
-
这段代码无法编译,
this.alertsSwitchEl在ngAfterViewChecked内部被访问,但它没有在任何地方定义。 -
@uminder - 抱歉,我在发布时更改了变量名。 this.alertsSwitchEl 应该是“mySwitchEl”。更新了我的帖子
-
上面的代码工作正常。其他地方可能有问题。创建一个堆栈闪电战。
-
@MaihanNijat - 代码有效,但单元测试对我来说失败了。单元测试对你有用吗?
标签: angular angular7 karma-jasmine