"Cannot assign to var because it is a read-only property." 在 angular 中使用 Jasmine 测试框架进行测试

"Cannot assign to var because it is a read-only property." in angular test using Jasmine Test Framework

我在 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;
}

在为同一服务编写测试时,如何为 timeIntervals 赋值?

我所做的是:

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService,
      ]
    });
    service = TestBed.get(MyService);
  });

it('should generate total 7 menu items for dropdown', () => {
    const timeIntervals = 'timeIntervals';
    service[timeIntervals] = timeLists;
    const generatedMenu = service.getTimeIntervalMenuItem();
    expect(generatedMenu.length).toBe(7);
  });

const timeLists = {
  3: '3',
  5: '5',
  10: '10',
  15: '15',
  20: '20',
  30: '30',
  60: '60'
};

我得到的错误是:

Cannot assign to 'timeIntervals' because it is a read-only property.

如何为 timeIntervals 赋值以便我可以测试我的方法

我通过

找到了解决方案

Object.defineProperty

代码:

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

您可以使用

JavaScript : Object Writable attribute, for more informations please refer to : Object.defineProperty()

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

如果您想查看您的属性的描述you can use

Object.getOwnPropertyDescriptor()