6

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.

1 Answer 1

21

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
   });
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is a nice answer but it still needs to call fixture.detectChanges() before the "should create". (As that's what creates the actual component, otherwise you're just testing TestBed.createComponent)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.