我正在尝试用笑话来测试localStorage:
it("changes the localStorage", () => {
const changeLocale = (languageLocale) => {
localStorage.setItem("language", languageLocale);
return {
type: "CHANGE_LOCALE",
locale: languageLocale
};
}
const locale = "de";
localStorage.clear();
changeLocale(locale);
expect(localStorage.setItem).toHaveBeenLastCalledWith(LOCAL_LANG, locale);
expect(localStorage.__STORE__[LOCAL_LANG]).toBe(locale);
});
当我尝试使用npm run test
运行它时,它返回如下错误:
expect(jest.fn())[.not].toHaveBeenLastCalledWith()
jest.fn() value must be a mock function or spy.
Received:
function: [Function setItem]
33 | changeLocale(locale);
34 |
> 35 | expect(localStorage.setItem).toHaveBeenLastCalledWith(LOCAL_LANG, locale);
| ^
36 | expect(localStorage.__STORE__[LOCAL_LANG]).toBe(locale);
37 | });
38 | });
我使用jest-localstorage-mock。您能否指出为什么我会收到该错误?谢谢。
答案 0 :(得分:0)
我决定摆脱jest-localstorage-mock
的用法。
相反,我这样做是spyOn
:
jest.spyOn(Storage.prototype, 'setItem');
jest.spyOn(Storage.prototype, 'getItem');
因此整个解决方案如下:
it('changes the localStorage', () => {
const changeLocale = languageLocale => {
localStorage.setItem('language', languageLocale);
return {
type: 'CHANGE_LOCALE',
locale: languageLocale
};
}
const locale = 'de';
jest.spyOn(Storage.prototype, 'setItem');
jest.spyOn(Storage.prototype, 'getItem');
localStorage.clear();
changeLocale(locale);
expect(localStorage.setItem).toHaveBeenLastCalledWith(LOCAL_LANG, locale);
expect(localStorage.getItem(LOCAL_LANG)).toBe(locale);
});
希望对某人有帮助:)