johannesMatevosyan
johannesMatevosyan

Reputation: 2228

How test function call inside ngOnChanges in angular jasmine?

I have a child component in angular app which calls function in ngOnChanges lifecycle hook.

export class GameComponent implements OnInit, OnChanges { 

   ngOnChanges(changes: SimpleChanges) {
     this.generateRandomIcon();
   }

   generateRandomIcon(): void {
     //some code goes here...
   }
}

Now I am trying to develop unit test to check if generateRandomIcon() function is called.

Here is the tests:

describe('GameComponent', () => {
  let component: GameComponent;
  let fixture: ComponentFixture<GameComponent>;
  let setGameItemImageSpy: any;
  let el: DebugElement;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [CommonModule],
      declarations: [GameComponent],
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(GameComponent);
        component = fixture.componentInstance;
        el = fixture.debugElement;
      });
  });

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

  it('should check if generateRandomIcon was called in ngOnChanges lifecycle hook', () => {
    setGameItemImageSpy = jasmine.createSpyObj(GameComponent, [
      'generateRandomIcon',
    ]);
    spyOn(component, 'ngOnChanges');

    setGameItemImageSpy.generateRandomIcon();
    expect(setGameItemImageSpy.generateRandomIcon).toHaveBeenCalled();
    expect(setGameItemImageSpy.generateRandomIcon).toHaveBeenCalledTimes(1);
  });
});

When unit tests is running then everything is ok, but anyway when I measure the coverage of tests then this part is not covered.

enter image description here

So, what I am doing wrong?

Upvotes: 3

Views: 4364

Answers (1)

Andrei
Andrei

Reputation: 12196

you should explicitly call change detection. If you do - Angular will call your component hooks.

  it('should check if generateRandomIcon was called in ngOnChanges lifecycle hook', () => {
    const generateRandomIconSpy = spyOn(component, 'generateRandomIcon');
    fixture.detectChanges();

    expect(generateRandomIconSpy ).toHaveBeenCalledTimes(1);
  });

Upvotes: 3

Related Questions