angular - Jasmine 存根函数导致类型错误“......不是函数”
问题描述
我正在尝试从我的测试中的“NavigationService”中存根一个函数。
正如您在下面看到的,我想使用我的 NavigationServiceStub 而不是 NavigationService。NavigationService 有一个名为“configureTargetScreensForNetworkConfiguration”的方法,我在存根中对其进行了模拟。
有了这个设置,我得到了 Error TypeError: this.navigationService.configureTargetScreensForNetworkConfigurationis not a function。我错过了什么吗?
describe('NetworkDevicesComponent', () => {
...
beforeEach(waitForAsync(() => {
networkServiceSpy = jasmine.createSpyObj('NetworkService', ['getNetworkDevices']);
networkServiceSpy.getNetworkDevices.and.returnValue(
of([
{type: NetworkType.WLAN, state: NetworkState.CONNECTING, links: null}
])
);
TestBed.configureTestingModule({
declarations: [
NetworkDevicesComponent
],
imports: [
RouterTestingModule
],
providers: [
{provide: NetworkService, useValue: networkServiceSpy},
{provide: NavigationService, useValue: NavigationServiceStub}
]
}).compileComponents();
}));
...
@Injectable()
export class NavigationService {
...
public configureTargetScreensForNetworkConfiguration(params: ParamMap): void {
if (this.hasNetworkTargetScreenParams(params)) {
this.setTargetScreensForNetworkConfiguration(params.get('backwardUrl'), params.get('forwardUrl'));
this.staticNetworkNavigationEnabled = true;
} else {
this.setTargetScreensForNetworkConfiguration('../../', '../../network-devices');
this.staticNetworkNavigationEnabled = false;
}
console.log('configured network-setting urls with backwardUrl:', this.targetScreenBeforeNetworkConfiguration,
'forwardUrl:', this.targetScreenAfterNetworkConfiguration,
'static-routing:', this.staticNetworkNavigationEnabled);
}
...
}
export class NavigationServiceStub {
configureTargetScreensForNetworkConfiguration(params: ParamMap): void {
}
...
}
解决方案
由于存根是一个类,我认为您应该使用useClass
而不是useValue
存根。
尝试:
providers: [
{provide: NetworkService, useValue: networkServiceSpy},
// change the line below to do useClass instead of useValue
{provide: NavigationService, useClass: NavigationServiceStub}
]
推荐阅读
- mongodb - 按匹配过滤器的数组的最后一个元素中的值对文档进行排序。蒙古数据库
- sql - 格式不同时使用 LIKE 子句
- python - 使用远程身份验证服务器的 Authlib 令牌验证器
- php - 知道 curl cacert 是如何破坏我的 php 应用程序的吗?
- sql - SQL Server:如何从事务日志中获取更新前的值?
- python - Numpy searchsorted沿着许多维度?
- apache-kafka - 按需运行源连接器,而不是基于 poll.interval.ms
- java - Appium - 我在截屏时收到空消息
- mosaic - 马赛克(1.8.3)的新更新在mac上不能用吗?
- html - Bootstrap/CSS:卡片正文中的单独标题和段落