Search code examples
angularunit-testingfixtures

How to list classList? Angular (unit testing). The class is given by @Input() @HostBinding('class.isBigButton') isBigButton = false;


component:

@Input() 
@HostBinding('class.isBigButton') isBigButton = false;

.spec.ts file:

component.isBigButton = true;
fixture.detectChanges();

This isBigButton class works fine in the app, then I wanted to write unit tests for that, but I could not find isBigButton class

I wanted to use .classList.contains('isBigButton')) to test

isBigButton class inside :host of .scss file (my isBigButton class is written there)

:host {
  &.isBigButton {
    
  }

By using console.log I searched this isBigButton class inside fixture.debugElement and fixture.nativeElement => could not find isBigButton class.

Why?


Solution

  • You most likely need to wrap this component into a host component for this to work.

    If the component is:

    @Component({
      ....
      selector: 'my-component',
    });
    export class MyComponent {
      @Input() 
      @HostBinding('class.isBigButton') isBigButton = false;
    }
    

    Then in your test, create a HostComponent that houses MyComponent.

    @Component({
      template: '<my-component [isBigButton]="isBigButton"></mycomponent>
    })
    class TestHostComponent {
      isBigButton: boolean;
    }
    

    Make sure you create TestHostComponent as the component to test.

    You can do something like the following.

    describe('MyComponent with greeter', () => {
      let fixture: ComponentFixture<TestHostComponent>;
      let component: TestHostComponent;
    
      beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
          declarations: [TestHostComponent, MyComponent]
        }).compileComponent();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(TestHostComponent);
        component = fixture.componentInstance;
      });
    
      it('should do xyz', () => {
        component.isBigButton = true;
        
        fixture.detectChanges();
    
        const isBigButton = fixture.debugElement.query(By.css('.isBigButton'));
        expect(isBigButton).toBeTruthy();
      });
    });
    
      @Component({
        template: '<my-component [isBigButton]="isBigButton"></my-component>
      })
      class TestHostComponent {
        isBigButton: boolean;
      }