简体   繁体   中英

How do I deal with a JSON.parse error coming from a Test in react when trying to mock localStorage?

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);
  });
});

The implementation of getItem needs to be updated to work the same as the standard implementation. So instead of:

global.Storage.prototype.getItem = jest.fn((key) => mockStorage[key]);

It should be something along the lines of

global.Storage.prototype.getItem = jest.fn((key) => mockStorage[key] ?? null);

So that if a key is not present, null is returned rather than undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM