![](/img/trans.png)
[英]Angular HttpParams to object, Object.defineProperty creates property but is out of scope
[英]Ensure spyOnProperty creates configurable properties with Object.defineProperty
在升級到 Angular 9(從 8.1)和 Typescript 3.7(從 <3.6)時,我遇到了spyOnProperty
的問題
我的服務看起來像:
class Backend {
public get baseURL(): string {
return 'http://baseurl.com/';
}
}
我在升級前運行的測試將spyOnProperty
spyOnProperty(backend, 'baseURL', 'get').and.returnValue('http://new');
但是,我現在收到此錯誤:
Error: <spyOnProperty> : baseURL is not declared configurable
Usage: spyOnProperty(<object>, <propName>, [accessType])
我知道我需要將Object.defineProperty
為可configurable: true
,因為在單步執行 Jasmine 時,我看到它在以下位置失敗:
if (!descriptor.configurable) {
throw new Error(
getErrorMsg(propertyName + ' is not declared configurable')
);
}
descriptor
由descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
創建descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
所以在 Javascript 中我想:
Object.defineProperty(backend.prototpye, 'baseURL', {value: 'http://new', configurable: true});
以確保可以監視此屬性。
但是,我的問題是如何使用 Typescript 應用相同的配置。 我曾嘗試再次運行Object.defineProperty
但我收到錯誤defineproperty Cannot redefine property
,這對於為什么首先進行檢查是有道理的。
我嘗試使用此處定義的建議的可configurable
裝飾器:
function configurable(value: boolean) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.configurable = value;
};
}
但這不起作用,還要注意,當我在上面的方法中放置斷點時, descriptor.configurable
在分配value
之前實際上已經設置為true
。 所以我不確定是什么導致了測試中的原始錯誤。
我錯過了一些關於創建我的測試的附加信息。 要創建我正在使用的注入服務的實例,請使用ts-mockito創建每個類的instance()
。
我認為正是對instance()
調用將屬性創建為不可配置的。
有效地:
service = new Service(instance(new Backend));
變成:
service = new Service(new Backend);
解決問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.