This is the error I'm getting.
FAIL src/tests/Game.test.js
Game Component
× Renders game part of the component when lastPlayed is null (157 ms)
● Game Component › Renders game part of the component when lastPlayed is null
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
19 | function getTimeDiff() {
20 | let currentDay = new Date().toISOString();
> 21 | let prevPlay = JSON.parse(localStorage.getItem("lastplayed"));
| ^
22 | let diff = differenceInHours(parseISO(currentDay), parseISO(prevPlay));
23 | console.log(currentDay + " and " + prevPlay);
24 |
at getTimeDiff (src/Game.js:21:25)
However, technically if the mock was working properly, and lastplayed was set to null, the function getTimeDiff() shouldn't even be called
This is the conditional within the Game component:
return(
<div>
{localStorage.getItem("lastplayed") === null || getTimeDiff() >= 24 ? (<SubComponent/>):(<AnotherComponent/>) }
</div>
)
this is my test file, I got the mockStorage code from here
let mockStorage = {};
beforeAll(() => {
global.Storage.prototype.setItem = jest.fn((key, value) => {
mockStorage[key] = value;
});
global.Storage.prototype.getItem = jest.fn((key) => mockStorage[key]);
});
beforeEach(() => {
mockStorage = {};
});
afterAll(() => {
global.Storage.prototype.setItem.mockReset();
global.Storage.prototype.getItem.mockReset();
});
afterEach(cleanup);
describe("Game Component", () => {
it("Renders game part of the component when lastPlayed is null", () => {
localStorage.setItem("lastPlayed", null);
render(<Game />);
expect(screen.getByTestId("title-header")).toBeInTheDocument();
expect(screen.getByTestId("game-status-div")).toBeInTheDocument();
expect(screen.queryByText("That's it for today")).not.toBeInTheDocument();
expect(global.Storage.prototype.setItem).toHaveBeenCalledOnce();
expect(mockStorage["lastPlayed"]).toEqual(null);
});
});
Unexpected token u in JSON at position 0- most likely the thing that is being "parsed" isundefined.... that's where theucomes from - though ...localStorage.getItemnever returnsundefined... so that's a mystery - unless that item in localStorage is the string"undefined"I guess - Jaromanda Xglobal.Storage? It appears (from a brief glance through the linked code) it can returnundefinedquite readily. - Heretic MonkeylocalStorage.getItem("lastplayed")- oh, right ... i see what you mean - Jaromanda XmockStorageis there at all then... Oh, I see,localStoragecallswindow.Storage.prototype.getItem/setItem- Heretic Monkey