angular - 角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();
})
解决方案
经过一番尝试并失败后,我注意到如果我像下面这样重新安排订单,它会起作用
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');
推荐阅读
- javascript - TypeScript:是否可以动态更改枚举的值
- c++ - 错误 LNK2019 未解析的外部符号 __imp_freopen 在函数 qh_initflags 中引用
- oracle - 将 ETL 作业从 IBM Datastage 转换为 Apache Spark
- java - 使用 IsEmpty() 和 isFull() JUnit 测试来测试堆栈是否为空/满
- html - 带有边框半径的 css 图像
- node.js - Cpanel 上的 Nodejs 环境变量
- java - 为什么java队列在某些情况下无法轮询数据?
- python - 为什么我在 pygame 上的圈子不断消失和重新生成?
- git - 将两台不同机器上的两个预先存在的本地文件夹合并到一个共享的在线存储库中
- unreal-engine4 - 在虚幻引擎 4 中构建光照后的黑色树叶