";无法赋值给var,因为它是只读属性。";在使用Jasmine测试框架的角度测试中 [英] "Cannot assign to var because it is a read-only property." in angular test using Jasmine Test Framework
本文介绍了";无法赋值给var,因为它是只读属性。";在使用Jasmine测试框架的角度测试中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在ANGLE中的一个服务中有一个只读属性:
@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;
}
为同一服务编写测试时,如何为timeInterval赋值?
我做的是:
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'
};
我收到错误,原因是:
无法分配给"timeInterval",因为它是只读属性。
如何为timeInterval赋值,以便测试我的方法
推荐答案
我通过使用
找到了解决方案Object.fineProperty
编码:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MyService
]
});
service = TestBed.get(MyService);
const timeIntervals = 'timeIntervals';
Object.defineProperty(service, timeIntervals, { value: timeLists });
});
这篇关于";无法赋值给var,因为它是只读属性。";在使用Jasmine测试框架的角度测试中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文