簡體   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