首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么Angular 8单元测试中的viewChild引用未定义

为什么Angular 8单元测试中的viewChild引用未定义
EN

Stack Overflow用户
提问于 2019-06-14 22:55:42
回答 1查看 3.4K关注 0票数 2

我在我的项目中使用Angular 8,但是当我在单元测试中有一个带有ViewChild引用的组件时,我在单元测试中遇到了问题-单元测试是未定义的。有什么帮助吗?

我有一个组件

代码语言:javascript
复制
@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);
  }
}

我对这个组件的单元测试是

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

发布于 2019-06-20 04:41:03

显然,@ViewChild("measurementBoxStar") measurementBox: ElementRef;没有返回任何元素。这可能是因为*ngIf="valueStar !== -1 && measurementName === ''"在测试中的计算结果为false。因此,如下所示更改您的规范应该可以解决这个问题。

代码语言:javascript
复制
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");
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56600655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档