gpt4 book ai didi

angular - 如何以 Angular 创建测试用例以检查本地存储中是否存在值

转载 作者:行者123 更新时间:2023-12-04 09:23:57 25 4
gpt4 key购买 nike

我的 组件.ts 文件
ngOnInit() {

if (localStorage.getItem('distanceUnit' + this.userMobile) == 'km') {
this.toggleSlider = false;
}
}
setUnit(): 无效 {
if (this.toggleSlider) {
this.toggleSlider = false;
localStorage.setItem('distanceUnit' + this.userMobile, 'km');
} else {
this.toggleSlider = true;
localStorage.setItem('distanceUnit' + this.userMobile, 'mi');
}
}
我的测试用例在 spec.ts 文件
it('Toggle button should be false in case distance unit km', () => {
component.toggleSlider = false
expect(component.toggleSlider).toBe(false);
});

最佳答案

检查以下代码 本地存储测试用例。

 beforeAll( () => {
let data= {};
const myLocalStorage = {
getItem: (key: string): string => {
return key in store ? store[key] : null;
},
setItem: (key: string, value: string) => {
data[key] = `${value}`;
},
removeItem: (key: string) => {
delete data[key];
},
clear: () => {
data= {};
}
};
spyOn(localStorage, 'getItem')
.and.callFake(myLocalStorage .getItem);
spyOn(localStorage, 'setItem')
.and.callFake(myLocalStorage .setItem);
spyOn(localStorage, 'removeItem')
.and.callFake(myLocalStorage .removeItem);
spyOn(localStorage, 'clear')
.and.callFake(myLocalStorage .clear);

localStorage.setItem('localStorageKey', 'value')
})

关于angular - 如何以 Angular 创建测试用例以检查本地存储中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63051890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com