繁体   English   中英

Jasmine 通过获取属性监视服务

[英]Jasmine spy on service with get property

我有一个AuthenticationService公开一个 get 属性:

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  private currentUserSubject: BehaviorSubject<AuthenticatedUserModel>;

  get currentUserValue(): AuthenticatedUserModel {
    return this.currentUserSubject.value;
  }
}

此服务用于我创建的自定义 pipe。 为了验证 pipe 是否按预期工作,我试图编写一些测试,但我正在努力模拟 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 帖子中的一个答案指出这是一个类型问题。 我认为将 object 称为spy可以解决此问题,但事实并非如此。

希望你们能帮助我或指出我正确的方向。

您应该使用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM