0

I am unable to test else condition in my code as Unable to change value of input(). Please help. Once I pass data in spec.ts unable to assign other data

@Input() data: any;
ngOnInit(): void {
    if (this.data !== undefined) {
      this.fn1()
    }
    else {
      this fn2()
    }
  }```
Orpita
  • 11
  • 2
  • 1
    Please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – Ascendise Oct 13 '22 at 14:21

1 Answers1

0

Most likely you are calling fixture.detectChanges before you are setting component.data

it('populated data should do things and stuff', () => {
  // create your component, hopefully in the beforeEach
  const fixture = TestBed.createComponent(AppComponent);
  const component = fixture.componentInstance;

  // set the input BEFORE you call fixture.detectChanges the first time
  const data = {};
  component.data = data
 
  fixture.detectChanges(); // ngOnInit now fires

  // assert what you expect to happen
});

Test made as simple as possible. I'd prefer the approach where you use a fake TestHost that can pass the input to your component like it would when running. Here is the documentation around that. I gave an example answer here

Wesley Trantham
  • 1,154
  • 6
  • 12