0

I'm writing unit tests with Jasmine in Angular.

export class Component extends AnotherComponent implements OnInit {
  @Input() public configuration: string;
  @Input() public data: Data;
  private _model: IConfiguration;
  public get model(): IConfiguration {
    return this._model;
  }
  constructor(injector: Injector, private _value: Value) {
    super(injector);
  }
  public ngOnInit() {
    super.ngOnInit();
  }
  public async ngOnChanges(changes: SimpleChanges) {
    super.ngOnChanges(changes);
    if (changes && changes['configuration']) {
      this.model = await this.value.doSomething(this.configuration);
    }
  }

I want to test the ngOnChanges() method, specifically the if inside.
This is my test code

describe('Component', () => {
  let component: Component;
  let fixture: ComponentFixture<Component>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [Module, TranslateModule.forRoot()],
      declarations: [Component]
    })
      .compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    component = fixture.componentInstance;
  });

  it('Expect model to be not undefined', () => {
    const configuration = 'configurationValue';
    component.configuration = configuration;
    component.data = new SampleData();
    fixture.detectCanges();
    expect(component.model).not.toBeUndefined();
  });
});

I do not understand why "component.model" is still undefined. I've also tried with fixture.whenStable() but nothing changed.

it('model exist', (done) => {
    return fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.model).not.toBeUndefined();
      done();
    });

What am I doing wrong? Thanks for the help.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
AmD
  • 399
  • 2
  • 12

1 Answers1

0

The only way ngOnChanges gets called is if you wrap your component inside of a host component and change the properties of this host component that are bounded to your component as inputs.

You can also call it manually.

it('Expect model to be not undefined', async (done) => { // add async done here
    const configuration = 'configurationValue';
    component.configuration = configuration;
    component.data = new SampleData();
    fixture.detectCanges();
    spyOn(value, 'doSomething');
    await component.ngOnChanges({ configuration: {} });
    expect(value.doSomething).toHaveBeenCalledWith({});
    expect(component.model).not.toBeUndefined();
  });

Check out this link and the other answers.

AliF50
  • 16,947
  • 1
  • 21
  • 37