我正在使用Jest来测试我的反应应用程序,我有一个组件,可以使用componentwillmount
方法从localStorage解析一些状态数据,并将其保存到它的状态。
像这样:
componentWillMount() {
let keys = Object.keys(localStorage);
let data = [];
keys.map((key) => {
if(Date.parse(key) && moment(key).isValid()) {
let item = JSON.parse(localStorage.getItem(key));
item['date'] = moment(key);
data.push(item)
}
});
this.setState({
data: data
})
}
我正在使用jest-localstorage-mock
软件包来模拟localStorage for Jest,每当我调用localStorage.setItem(KEY, VALUE)
时,它都会被放置在localStorage.__STORE__
中。这是测试。
it('Should get data from localstorage', () => {
let obj = {
date: "2017-12-23T17:33:33.265Z",
obj: {"pain":"3","work":"9","sleep":"8","notes":"notes","pressure":1025
}};
localStorage.setItem(obj.date, JSON.stringify(obj.obj));
expect(localStorage.setItem).toHaveBeenCalledTimes(1); // PASSES
const wrapper = shallow(<Main />);
console.log(localStorage.__STORE__); // LOOKS LIKE IT SHOULD
console.log(wrapper.state()); // EMPTY! because all the data is placed into localStorage.__STORE__
expect(localStorage.getItem).toHaveBeenCalledTimes(1) // FAILS
})
如何让这两个一起工作,以便我可以测试从localStorage检索