如何使用Jest测试localStorage



我嘲笑localStorage在另一个威胁上的建议,但我无法让测试发挥作用,我尝试了多次,但都没有成功。

这是模拟

class LocalStorageMock {
constructor() {
this.store = {};
}
clear() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value.toString();
}
removeItem(key) {
delete this.store[key];
}
}
这是我试图测试的功能。

const setToLS = (target, value) => {
localStorage.setItem(target, JSON.stringify(value));
};
const saveToLS = (target, item) => {
let items;
if (localStorage.getItem(target)) {
items = utilities.addItem(JSON.parse(localStorage.getItem(target)), item);
} else {
items = utilities.addItem([], item);
}
setToLS(target, items);
};

这是我不能上班的测试。

describe('utilitiesLS', () => {
describe('saveToLS', () => {
it('should save item to LS')', () => {
const target = 'recipes';
const item = { name: 'salat', ingredients: 'spinach', id: 1 };
utilitiesLS.saveToLS(target, item)
expect(localStorage.store).toMatch( '{"recipes": [{"id": 1, "ingredient": "spinach", "recipeName": "salat"}]}'
)
});
});
});

这就是错误。

expect(string)[.not].toMatch(expected)
string value must be a string.
Received: undefined
29 |       const item = { recipeName: 'salat', ingredients: 'spinach', id: 1 };
30 |       utilitiesLS.saveToLS(target, item)
> 31 |       expect(localStorage.store).toMatch( '{"recipes": [{"id": 1, "ingredient": "spinach", "recipe
Name": "salat"}]}'
|                                  ^
32 |       )
33 |     });
34 |   });

问题出在您的测试上。

LocalStorageMock.store是一个对象,但您的测试expect(localStorage.store).toMatch( '{"reci...正在测试它,看它是否是一个字符串。这就是为什么您的测试没有通过,因为对象与字符串不匹配。

要解决此问题,您应该测试:

expect(localStorage.store).toEqual({"recipes": [{"id": 1, "ingredient": "spinach", "recipeName": "salat"}]})

注意到localStorage.store是未定义的,这表明您也没有获得测试正在使用的mock的构造实例。

n.b.如果您试图模拟本地存储,请考虑预先构建、测试和记录的方法之一,例如:https://www.npmjs.com/package/jest-localstorage-mock

最新更新