本文介绍了为什么未定义 Angular 8 单元测试中的 viewChild 参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用 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");
});

当我运行单元测试时,我收到此错误 Jasmine 错误

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 参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:01