我已经按照建议对另一个威胁进行了模拟,但是我无法使测试正常工作,但尝试了多次却没有成功。
这是模拟
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 | });
答案 0 :(得分:1)
问题在于您的测试。
LocalStorageMock.store
是一个对象,但是您的测试expect(localStorage.store).toMatch( '{"reci...
正在对其进行测试以查看它是否是字符串。这就是为什么测试没有通过的原因,因为对象与字符串不匹配。
要解决此问题,您应该测试:
expect(localStorage.store).toEqual({"recipes": [{"id": 1, "ingredient": "spinach", "recipeName": "salat"}]})
注意到localStorage.store是未定义的,这表明您也没有获得测试所使用的模拟实例的构造实例。
n.b。如果要模拟本地存储,请考虑以下一种预先构建,测试和记录的方法: https://www.npmjs.com/package/jest-localstorage-mock