繁体   English   中英

确保 spyOnProperty 使用 Object.defineProperty 创建可配置的属性

[英]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')
  );
}

descriptordescriptor = 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.

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