Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular &引用;无法分配给var,因为它是只读属性。”;使用Jasmine测试框架进行角度测试_Angular_Typescript_Karma Jasmine_Karma Runner - Fatal编程技术网

Angular &引用;无法分配给var,因为它是只读属性。”;使用Jasmine测试框架进行角度测试

Angular &引用;无法分配给var,因为它是只读属性。”;使用Jasmine测试框架进行角度测试,angular,typescript,karma-jasmine,karma-runner,Angular,Typescript,Karma Jasmine,Karma Runner,我在angular中的一个服务中有一个只读属性: @Injectable({ providedIn: 'root' }) export class MyService { private readonly timeIntervals: any; } constructor(private readonly config: AppConfig) { this.timeIntervals = this.config.getResourceByKey(this.timeInterv

我在angular中的一个服务中有一个只读属性:

@Injectable({
  providedIn: 'root'
})

export class MyService {
  private readonly timeIntervals: any;
}

constructor(private readonly config: AppConfig) {
    this.timeIntervals = this.config.getResourceByKey(this.timeIntervalString);
}



getTimeIntervalMenuItem(): Array<IElementData>{
    const menuListItems = new Array<IElementData>();
    let index = 0;
    for (const item of Object.keys(this.timeIntervals)) {
      menuListItems.push({
        id: this.menuItem + index.toString(),
        label: this.timeIntervals[item].toString()
      });
      index++;
    }
    return menuListItems;
  }

export interface IElementData {
    label?: string;
    value?: string;
    id?: string;
    active?: string;
}
我得到的错误如下:

无法分配给“时间间隔”,因为它是只读属性


如何为时间间隔赋值,以便测试我的方法

我通过使用

Object.defineProperty

代码:

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService
      ]
    });
    service = TestBed.get(MyService);
    const timeIntervals = 'timeIntervals';
    Object.defineProperty(service, timeIntervals, { value: timeLists });
  });

我用计算机找出了解决办法

Object.defineProperty

代码:

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService
      ]
    });
    service = TestBed.get(MyService);
    const timeIntervals = 'timeIntervals';
    Object.defineProperty(service, timeIntervals, { value: timeLists });
  });
你可以用

JavaScript:对象可写属性,有关更多信息,请参阅:

如果您想查看您的属性描述

Object.getOwnPropertyDescriptor()

你可以用

JavaScript:对象可写属性,有关更多信息,请参阅:

如果您想查看您的属性描述

Object.getOwnPropertyDescriptor()

Object.defineProperty(service, timeIntervals, { writable: true});