Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing angular component with @input

I have an angular component which has an @input attribute and processes this on the ngOnInit. Normally when unit testing an @input I just give it as component.inputproperty=value but in this case I cannot since its being used on the ngOnInit. How do I provide this input value in the .spec.ts file. The only option I can think of is to create a test host component, but I really don't want to go down this path if there is an easier method.

like image 907
pandith padaya Avatar asked Aug 24 '26 22:08

pandith padaya


1 Answers

Doing a test host component is a way to do it but I understand it can be too much work.

The ngOnInit of a component gets called on the first fixture.detectChanges() after TestBed.createComponent(...).

So to make sure it is populated in the ngOnInit, set it before the first fixture.detectChanges().

Example:

fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
component.inputproperty = value; // set the value here
fixture.detectChanges(); // first fixture.detectChanges call after createComponent will call ngOnInit

I assume all of that is in a beforeEach and if you want different values for inputproperty, you have to get creative with describes and beforeEach.

For instance:

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

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

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

  it('should create', () => {
    expect(component).toBeDefined();
  });

  describe('inputproperty is blahBlah', () => {
   beforeEach(() => {
     component.inputproperty = 'blahBlah';
     fixture.detectChanges();
   });

   it('should do xyz if inputProperty is blahBlah', () => {
     // test when inputproperty is blahBlah
   });
  });

  describe('inputproperty is abc', () => {
   beforeEach(() => {
     component.inputproperty = 'abc';
     fixture.detectChanges();
   });

   it('should do xyz if inputProperty is abc', () => {
     // test when inputproperty is abc
   });
  });
});
like image 196
AliF50 Avatar answered Aug 28 '26 08:08

AliF50



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!