angular - 茉莉花间谍服务获得财产
问题描述
我有一个AuthenticationService
公开 get 属性:
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<AuthenticatedUserModel>;
get currentUserValue(): AuthenticatedUserModel {
return this.currentUserSubject.value;
}
}
此服务用于我创建的自定义管道中。为了验证管道是否按预期工作,我试图编写一些测试,但我正在努力模拟 get 属性。我发现这篇Stackoverflow 帖子非常有帮助。我尝试了以下所有选项来模拟 get 属性,但不幸的是到目前为止还没有运气。
// Property currentUserValue does not have access type get
spyOnProperty(authenticationServiceSpy, 'currentUserValue', 'get').and.returnValue(undefined);
// Cannot read property 'and' of undefined
(Object.getOwnPropertyDescriptor(authenticationServiceSpy, 'currentUserValue')?.get as jasmine.Spy<() => AuthenticatedUserModel>).and.returnValue(undefined);
((Object.getOwnPropertyDescriptor(authenticationServiceSpy, 'currentUserValue')?.get as jasmine.Spy<() => AuthenticatedUserModel>) as jasmine.Spy).and.returnValue(undefined);
我提到的 Stackoverflow 帖子中的一个答案指出这是一个类型问题。我认为将对象称为 aspy
可以解决此问题,但事实并非如此。
希望你们能帮助我或指出我正确的方向。
解决方案
您应该使用 spyOnProperty :
it("allows you to create spies for either type", function() {
spyOnProperty(someObject, "myValue", "get").and.returnValue(30);
spyOnProperty(someObject, "myValue", "set").and.callThrough();
});
你可以在这里阅读文档: https ://jasmine.github.io/tutorials/spying_on_properties
推荐阅读
- css - 从不同来源多次导入相同的字体有害吗?
- angular - Angular 5过滤管
- apache-spark - 如何解释 Spark 中precisionByThreshold 的返回结果?
- rust - 如何删除我在 Rust 中无权访问的目录?
- google-compute-engine - 在不关闭实例的情况下调整云 VM 磁盘大小(谷歌云)
- python - Keras:使用灰度蒙版和 ImageDataGenerator 类进行图像分割
- mdc-components - 如何在 lit 元素中使用 MDC 组件?
- r - 在 SpatialPolygonDataFrame 中计算人口
- migration - 用于优化构建的 Angular 6 升级运行时问题
- scala - 如何创建涉及某些功能在范围内的“块”的 DSL?