【发布时间】:2019-10-29 05:42:28
【问题描述】:
我在我的项目中使用 Angular 8,但是当我在单元测试中有一个带有 ViewChild Ref 的组件未定义时,我遇到了单元测试问题。任何帮助
我有一个组件
@Component({
selector: "app-rating-star",
templateUrl: "./rating-star.component.html",
styleUrls: ["./rating-star.component.scss"],
encapsulation: ViewEncapsulation.None
})
export class RatingStarComponent implements OnInit, AfterViewInit {
@ViewChild("measurementBoxStar") measurementBox: ElementRef;
constructor(private _render: Renderer2) {}
ngOnInit() {}
ngAfterViewInit() {
this._render.addClass(this.measurementBox.nativeElement, newClass);
}
}
我对这个组件的单元测试是
beforeEach(async(() => {
TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
declarations: [RatingStarComponent],
providers: [
{
provide: Renderer2,
useClass: rootRendererMock
}
]
}).compileComponents();
fixture = TestBed.createComponent(RatingStarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it("check Input value for Box in red", () => {
component = fixture.componentInstance;
component.ngOnInit();
fixture.detectChanges();
component.ngAfterViewInit();
expect(component.valueStar).toEqual(1.702);
fixture.detectChanges();
expect(component.measurementBox.nativeElement.querySelector("span").innerText)
.toEqual("1.702");
});
当我运行单元测试时,我收到了这个错误Error for Jasmine
【问题讨论】:
-
能否分享rating-star.component.html的代码
-
嗨@ysf 我把它放在下面。
div *ngIf="valueStar !== -1 && measurementName === ''" class="label pt-4 pv-4 mx-8 label-box" #measurementBoxStar > <span>{{ valueStar }} </span> </div>
标签: unit-testing viewchild angular8