'Check LocaleStorage via Unit tests in React
I have been trying to mock my localeStorage with that library https://www.npmjs.com/package/jest-localstorage-mock But it always shows me the next mistake
SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse ()
Here is mine test
it('checks the locale cost element', () => {
const headerCoinCost = 544123.123543;
const KEY = "walletData",
VALUE = '[{"id":"bitcoin","name":"Bitcoin","price":"38953.6908005677844877","amount":"1"}]';
render(<HeaderWallet headerCoinCost={headerCoinCost} onClick={true ? true : false} ></HeaderWallet>);
const userWalletDifferenceElement = screen.getByTestId("user-wallet__different-cost-test");
expect(userWalletDifferenceElement).toBeInTheDocument();
dispatch(action.update(KEY, VALUE));
expect(localStorage.setItem).toHaveBeenLastCalledWith(KEY, VALUE);
expect(localStorage.__STORE__[KEY]).toBe(VALUE);
expect(Object.keys(localStorage.__STORE__).length).toBe(1);
expect(userWalletDifferenceElement).toHaveTextContent(544123.12);
});
component where I get mistake
export const getLocaleCost = () => {
let localCostArr = [];
let sum = 0;
let existingEntries = JSON.parse(localStorage.getItem("walletData"));
if (existingEntries == null) existingEntries = [];
existingEntries.map(el => {
localCostArr.push(el.price * el.amount)
});
for (let i = 0; i < localCostArr.length; i++) {
sum += +localCostArr[i];
};
return sum;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
