Angular &引用;无法分配给var,因为它是只读属性。”;使用Jasmine测试框架进行角度测试
我在angular中的一个服务中有一个只读属性: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
@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});