我一直在为我的项目使用反应。现在我试图使用localStorage作为我的主存储器,因为除了algolia之外没有任何数据库连接。
但我的localStorage代码现在无法通过其他测试(渲染测试等)并获得" TypeError:无法读取属性' getItem'未定义"当我试图在这行代码中访问我的本地存储时:
var collections = JSON.parse(window.localStorage.getItem(' collections'));
我想这是因为我试图创建一个组件,但localStorage仍未定义(或尚未定义)
这是我的代码,用于定义我的localStorage
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import Header from '../../components/header/header';
import Footer from '../../components/footer/footer';
import RecommendedCategory from '../../components/recommendedCategory/recommendedCategory';
import RecommendedItem from '../../components/recommendedItem/recommendedItem';
import './css/home.css';
class Home extends Component {
render() {
var collections, urlCollections;
if(window.localStorage.collections === undefined || window.localStorage.urlCollections === undefined){
collections = [];
urlCollections = [];
} else {
collections = JSON.parse(window.localStorage.getItem('collections'));
urlCollections = JSON.parse(window.localStorage.getItem('urlCollections'));
}
window.localStorage.setItem('collections', JSON.stringify(collections));
window.localStorage.setItem('urlCollections', JSON.stringify(urlCollections));
return (
<BrowserRouter>
<div className="Home">
<Header />
<div className="containerCategory">
<RecommendedCategory />
<RecommendedItem />
</div>
<Footer />
</div>
</BrowserRouter>
);
}
}
export default Home;
您是否知道如何在localStorage中获取项目而不会失败渲染测试?
答案 0 :(得分:0)
在使用mocha / jest / etc的节点中运行单元测试时,您将无法使用浏览器API(在您的情况下为def getFilesList(directoryName):
...
return filesList
# This will tell you if the item is a file or a directory.
def isDirectory(item):
...
return true/false
)。
您必须为相应的测试环境设置模拟浏览器API实现,这些实现不受环境本身的影响。
检查此答案,了解mocking localStorage的方法 可以实现。
答案 1 :(得分:0)
如果您的浏览器不支持localStorage,您可以通过添加条件来检查它是否在浏览器中可用,来克服错误
render() {
var collections, urlCollections;
if(typeof(Storage) !== "undefined"){
if(window.localStorage.collections === undefined || window.localStorage.urlCollections === undefined){
collections = [];
urlCollections = [];
} else {
collections = JSON.parse(window.localStorage.getItem('collections'));
urlCollections = JSON.parse(window.localStorage.getItem('urlCollections'));
}
window.localStorage.setItem('collections', JSON.stringify(collections));
window.localStorage.setItem('urlCollections', JSON.stringify(urlCollections));
}
return (
<BrowserRouter>
<div className="Home">
<Header />
<div className="containerCategory">
<RecommendedCategory />
<RecommendedItem />
</div>
<Footer />
</div>
</BrowserRouter>
);
}