首页 > 解决方案 > 角8,茉莉花: 找不到对象来监视 bind()

问题描述

对于我的 Angular 组件,我有一个基类,为了保持当前这个上下文,我有以下绑定代码。如果 I console.log,我可以看到updatePreference被调用,但 jasmine 无法检测到是否被调用。

如果我使用以下内容,我会在标题处收到错误

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();
})

标签: angularjasminebind

解决方案


经过一番尝试并失败后,我注意到如果我像下面这样重新安排订单,它会起作用

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');

推荐阅读