首页 > 解决方案 > 茉莉花间谍服务获得财产

问题描述

我有一个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可以解决此问题,但事实并非如此。

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

标签: angularjasminekarma-runner

解决方案


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


推荐阅读