Reputation: 23102
For my Angular component, I have a base class, and in order to keep current this context I have following binding code. If I console.log
, I can see updatePreference
is called, but jasmine cannot detect if it is called.
If I use following, I am getting error at the title
spyOn(fixture.componentInstance.updatePreference.prototype, 'bind').and.callThrough();
Is there anything missing on my setup?
Profile-component.ts extends Profile-base.ts
public ngOnInit(): void {
this.updatePreference = this.updatePreference.bind(this);
}
public openRemovePanel(itemGuid: string) {
super.openRemovePanel(itemGuid, this.updatePreference);
}
Profile-base.ts (base class)
public openRemovePanel(itemGuid: string, callbackFunction: (id: string, data: string) => void) {
….
callbackFunction(id, data);
}
Profile-component.spec.ts
fit('this should work', () => {
let fixture = TestBed.createComponent(ProfileComponent);
fixture.detectChanges();
// tried both of the following
spyOn(fixture.componentInstance.updatePreference.prototype, 'bind').and.callThrough();
spyOn(fixture.componentInstance, updatePreference).and.callThrough();
…...
// make a call to openRemovePanel, and that triggers updatePreference
……
// this does not work
expect(fixture.componentInstance.updatePreference).toHaveBeenCalled();
})
Upvotes: 2
Views: 1460
Reputation: 23102
After some try and fail, I noticed it works if I re-arrange order like below
let fixture = TestBed.createComponent(ProfileComponent);
// hold the spy reference
let spyReference = spyOn(fixture.componentInstance, updatePreference).and.callThrough();
// then trigger OnInit to do binding
fixture.detectChanges();
// then write your expection against spy reference
expect(spyReference ).toHaveBeenCalledWith('123', '456');
Upvotes: 2