jeudi 12 novembre 2020

How to test re-usable component element in angular app?

Problem is simple, i wanna make reusable, self tested component. How my code looks: HTML:

<div class="horizontal-menu-bar">
    <div id="#logotype" class="logotype">
        
    </div>
    <div  class="menu">
        <button 
            *ngFor="let menuElement of menuElements"
            id=
            >
            
        </button>
    </div>
</div>

Test:

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

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

  beforeEach(() => {
    fixture = TestBed.createComponent(HorizontalMenuComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
...
  it('should render appName', () => {
    component.appName = 'Test appName';
    const expected = 'Test appName';
    fixture.detectChanges();
    const element = fixture.debugElement.nativeElement.querySelector('#logotype');
    expect(element.innerHTML).toBe(expected);
  });
...
});

Ts:

@Component({
  selector: 'demo-horizontal-menu',
  templateUrl: './horizontal-menu.component.html',
  styleUrls: ['./horizontal-menu.component.scss']
})
export class HorizontalMenuComponent implements OnInit {

  @Input() appName: string;
  @Input() menuElements: MenuElements[];

  constructor() { }

  ngOnInit(): void {
  }

}

And my output:

HorizontalMenuComponent › should render appName TypeError: Cannot read property 'innerHTML' of null

I know where is problem but at this moment i don't have idea how to fix it. I should mock somehow test value into my component but how?

Aucun commentaire:

Enregistrer un commentaire