2

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

当我运行单元测试时,我收到了 Jasmine 的这个错误 Error

4

1 回答 1

1

显然@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");
});
于 2019-06-19T20:41:03.270 回答