Reputation: 2228
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.
So, what I am doing wrong?
Upvotes: 3
Views: 4364
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