Sha*_*ati 9 typescript karma-runner karma-jasmine angular
我在 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;
}
Run Code Online (Sandbox Code Playgroud)
在为同一服务编写测试时,如何为 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'
};
Run Code Online (Sandbox Code Playgroud)
我收到错误如下:
无法分配给“timeIntervals”,因为它是只读属性。
如何为 timeIntervals 分配值以便我可以测试我的方法
Sha*_*ati 18
我通过使用找到了解决方案
对象.defineProperty
代码:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MyService
]
});
service = TestBed.get(MyService);
const timeIntervals = 'timeIntervals';
Object.defineProperty(service, timeIntervals, { value: timeLists });
});
Run Code Online (Sandbox Code Playgroud)
您可以使用
JavaScript :对象可写属性,更多信息请参考:Object.defineProperty()
Object.defineProperty(service, timeIntervals, { writable: true});
Run Code Online (Sandbox Code Playgroud)
如果你想查看你的属性的描述,你可以使用
Object.getOwnPropertyDescriptor()
| 归档时间: |
|
| 查看次数: |
19062 次 |
| 最近记录: |