【问题标题】:Why viewChild reference on Angular 8 unit test is undefinded为什么 Angular 8 单元测试中的 viewChild 引用未定义
【发布时间】:2019-10-29 05:42:28
【问题描述】:

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

【问题讨论】:

  • 能否分享rating-star.component.html的代码
  • 嗨@ysf 我把它放在下面。 div *ngIf="valueStar !== -1 && measurementName === ''" class="label pt-4 pv-4 mx-8 label-box" #measurementBoxStar > <span>{{ valueStar }} </span> </div>

标签: unit-testing viewchild angular8


【解决方案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-10-19
  • 2020-03-25
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-26
  • 2023-02-17
  • 1970-01-01
相关资源
最近更新 更多