【问题标题】:Jasmine spy on service with get property茉莉花间谍服务获得财产
【发布时间】:2021-04-07 07:03:28
【问题描述】:

我有一个AuthenticationService,它公开了一个 get 属性:

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

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

此服务用于我创建的自定义管道中。为了验证管道是否按预期工作,我试图编写一些测试,但我正在努力模拟 get 属性。我发现这个Stackoverflow post 很有帮助。我尝试了以下所有选项来模拟 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 帖子中的一个答案指出这是一个类型问题。我认为将对象称为 spy 可以解决此问题,但事实并非如此。

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

【问题讨论】:

    标签: angular jasmine karma-runner


    【解决方案1】:

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

    【讨论】:

    • 不幸的是,我仍然遇到同样的错误。我错过了什么吗?
    猜你喜欢
    • 2020-01-28
    • 1970-01-01
    • 2014-01-25
    • 2012-08-15
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多