我在项目中使用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
答案 0 :(得分:0)
显然@ViewChild("measurementBoxStar") measurementBox: ElementRef;
不返回任何元素。可能是因为*ngIf="valueStar !== -1 && measurementName === ''"
在测试中的评估结果为false
。因此,按照以下方式更改规格应该可以解决问题。
it("check Input value for Box in red", () => {
component = fixture.componentInstance;
component.measurementName = "";
fixture.detectChanges();
expect(component.valueStar).toEqual(1.702);
expect(component.measurementBox.nativeElement.querySelector("span").innerText)
.toEqual("1.702");
});