我在我的项目中使用Angular 8,但是当我在单元测试中有一个带有ViewChild引用的组件时,我在单元测试中遇到了问题-单元测试是未定义的。有什么帮助吗?
我有一个组件
@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
发布于 2019-06-20 04:41:03
显然,@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");
});
https://stackoverflow.com/questions/56600655
复制相似问题