1

I have a component that dynamically changes it's role attribute via HostBinding:

export class TestComponent {
  @HostBinding('attr.role')
    get role() {
      return this.isListItem ? 'listitem' : null;
    };
  @Input() isListItem: boolean;
}

But I'm struggling to write unit tests to cover scenarios when isListItem is set to true/false/undefined.

For example, this doesn't work:

beforeEach(() => {
  fixture = MockRender(`
    <app-test-component>
    </app-test-component>
  `);
  debugElement = fixture.debugElement;
  component = fixture.componentInstance;
  el = debugElement.children[0].nativeElement;
  fixture.detectChanges();
});

it('should have the role `listitem` if isListItem is true', () => {
  component.isListItem = true;
  fixture.detectChanges();
  expect(el.getAttribute('role')).toEqual('listitem');
});

Here is the error I get.

Error: Expected null to equal 'listitem'.

I was hoping by setting isListItem to true, and then using fixture.detectChanges() it would change the HostBinding in the tested component, but it looks like it's not.

shrewdbeans
  • 11,971
  • 23
  • 69
  • 115

1 Answers1

1

You don't need a mock renderer - you can access the fixture directly -> fixture.nativeElement.getAttribute('role') should be what you are looking for. There's more on the fixture as well for other bound properties.

evanjmg
  • 3,465
  • 1
  • 14
  • 12