Angular单元测试中用Jasmine/Karma监视父类方法的问题
Angular子类用super调用父类方法的单元测试监视方案
为啥会失败?
你之前监视子类CustomDualListComponent原型的方法没用,是因为super.selectItem()会直接跳去父类DualListComponent的原型方法执行,根本不会经过子类的方法定义,所以子类原型上的 spy 抓不到调用。
直接这么改就行
别监视子类的方法,直接监视父类DualListComponent的原型方法:
// 改成监视父类的原型方法 const selectItemSpy = spyOn(DualListComponent.prototype, 'selectItem'); const shiftClickSpy = spyOn(DualListComponent.prototype, 'shiftClick'); // 实例化子类组件并触发onClickElement const component = fixture.componentInstance; component.onClickElement(false, testItem, { pick: true }, mockEvent, 0); // 验证调用参数是否正确 expect(selectItemSpy).toHaveBeenCalledWith(true, testItem); expect(shiftClickSpy).toHaveBeenCalledWith(mockEvent, 0, { pick: true }, testItem);
为啥这么管用?
super.selectItem(...)本质上等同于DualListComponent.prototype.selectItem.call(this, ...args),直接监视父类原型上的方法,就能精准捕获到子类通过super发起的调用,完全不用改组件代码。
注意点
- 要确保测试文件里正确导入了
DualListComponent,不然会找不到父类。 - 如果父类的方法是私有或受保护的,可能需要调整Angular测试配置(比如开启
emitDecoratorMetadata),但公共方法直接这么用就没问题。
内容的提问来源于stack exchange,提问作者Jarvis
相关产品推荐
相关产品推荐

