Angular test - Getting "TypeError: Cannot read property 'textContent' of null" on Karma

Angular test - Getting "TypeError: Cannot read property 'textContent' of null" on Karma

我在我的 Angular 应用程序上设置了几个测试,其中一个在尝试获取 HTML 元素时出现此错误:TypeError: Cannot read property 'textContent' of null

这是我的模板示例:

<div *ngIf="parentProps" class="detalhes-container">
  <!-- <p class="teste">teste</p> -->
  <div *ngFor="let info of parentProps.applicationsData; let i = index; trackBy: trackByFn">
    <p class="teste">teste</p>
  </div>
</div>

上面有两个 p 标签用于测试目的,第一个被注释(它工作正常),第二个是我想让它工作的。

spec.ts 脚本:

describe('ListDetailsComponent', () => {
  let component: ListDetailsComponent;
  let fixture: ComponentFixture<ListDetailsComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ ListDetailsComponent ]
    })
    .compileComponents();
  })

  beforeEach(() => {
    fixture = TestBed.createComponent(ListDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create list details', () => {
    expect(component).toBeTruthy();
  });

  it('functions', () => {
    component.parentProps = true
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement
    expect(compiled.querySelector('.teste').textContent).toContain('teste');
  })

});

我有两个 p 标签的原因是因为我意识到其中一个问题是由于 *ngIf 使用的 parentProps 属性,所以我设置在我的测试中它是 true,然后它起作用了,但是,在这个 *ngIf 之后我还有一个带有 *ngFor 的块,当我 运行 我的测试中有标签时这个循环我得到同样的错误,所以,我相信问题是 *ngFor。使用 *ngIf 我设法解决了这个问题,但我不知道如何解决 *ngFor 问题。

有一件事可能很重要,parentProps 确实是一个来自我通过 @Input.

接收的父组件的对象

我该如何解决?

你必须applicationsData对象上的数组,对象不能只是真实的。

尝试:

it('functions', () => {
    component.parentProps = { applicationsData: ['hello', 'world'] }; // mock applicationsData array.
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement
    expect(compiled.querySelector('.teste').textContent).toContain('teste');
  })