1

I am setting several tests on my Angular application and in one of them I am getting this error when trying to get a HTML element: TypeError: Cannot read property 'textContent' of null

This is a sample of my template:

<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>

There are two p tags on it for testing purposes, the first one is commented (it works fine) and the second one is the one I want to make it work.

spec.ts script:

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');
  })

});

The reason I have two p tags is because I realized that one of the problems is due the parentProps property used by the *ngIf, so I set it as true in my test, then it worked, however, after this *ngIf I also have a block with a *ngFor and when I run my test with the tag within this loop I get the same error, so, I believe the problem is the *ngFor. With the *ngIf I managed to turn around this, but I have no idea how to solve the *ngFor problem.

One thing that may be important, the parentProps is indeed an object comming from the parent component that I am receiving through an @Input.

How could I solve that?

1 Answer 1

2

You have to make applicationsData an array on the object, the object cannot just be true.

Try:

it('functions', () => {
    component.parentProps = { applicationsData: ['hello', 'world'] }; // mock applicationsData array.
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement
    expect(compiled.querySelector('.teste').textContent).toContain('teste');
  })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.