问题描述
我在项目中使用Angular 8,但是当单元测试中的ViewChild Ref组件未定义时,单元测试出现问题.任何帮助
I am using Angular 8 in my project but I have a problem with the unit-test when I have a component with ViewChild Ref in the unit-test is undefined. any help
我只有一个组成部分
@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);
}
}
我对此组件的单元测试是
and my unit-test for this component is
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");
});
运行单元测试时,收到此错误茉莉花错误
when I run the unit-test, I received this error Error for Jasmine
推荐答案
显然 @ViewChild("measurementBoxStar")measurementBox:ElementRef;
不返回任何元素.可能是因为 * ngIf ="valueStar!== -1&& measurementName ===''"
在测试中评估为 false
.因此,按如下所示更改规格应该可以解决问题.
obviously @ViewChild("measurementBoxStar") measurementBox: ElementRef;
is not returning any elements. it may be because *ngIf="valueStar !== -1 && measurementName === ''"
evaluates to false
in tests. So changing your spec as follows should fix the problem.
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");
});
这篇关于为什么未确定Angular 8单元测试上的viewChild参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!