对于我的Angular组件,我有一个基类,并且为了保持最新的this context,我有以下绑定代码。如果我是console.log
,则可以看到updatePreference
被调用,但是茉莉花无法检测到它是否被调用。
如果使用关注,标题出现错误
spyOn(fixture.componentInstance.updatePreference.prototype, 'bind').and.callThrough();
我的装置上缺少任何东西吗?
Profile-component.ts扩展了Profile-base.ts
public ngOnInit(): void {
this.updatePreference = this.updatePreference.bind(this);
}
public openRemovePanel(itemGuid: string) {
super.openRemovePanel(itemGuid, this.updatePreference);
}
Profile-base.ts(基类)
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();
})
经过一番尝试和失败之后,我发现如果重新排列如下所示的命令,它会起作用
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');