简体   繁体   中英

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.

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 have get creative with describe s 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
   });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM