简体   繁体   English

在尝试模拟 localStorage 时,如何处理来自 Test in react 的 JSON.parse 错误?

[英]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但是,从技术上讲,如果模拟工作正常,并且 lastplayed 设置为 null,则 function getTimeDiff() 甚至不应该被调用

This is the conditional within the Game component:这是 Game 组件中的条件:

return(
<div>
{localStorage.getItem("lastplayed") === null || getTimeDiff() >= 24 ? (<SubComponent/>):(<AnotherComponent/>) }
</div>
)

this is my test file, I got the mockStorage code from here这是我的测试文件,我从这里得到了 mockStorage 代码


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. getItem的实现需要更新以与标准实现相同。 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 .因此,如果键不存在,则返回null而不是undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用“dotnet new react -o my-app”中的默认代码时,为什么会出现 JSON.parse 错误? - Why do I get JSON.parse error when using default code from “dotnet new react -o my-app”? 尝试在简单对象上执行JSON.parse时出现“意外令牌”错误 - I am getting an “Unexpected token” error when trying to do JSON.parse on a simple object 如何从URL JSON.parse解析字符串(React Native) - How do I JSON.parse a string from URL (React Native) JSON.parse() 来自 localStorage 问题 - JSON.parse() from localStorage issue JSON.parse 在解析字符串时出现错误 - JSON.parse is giving me an error when I parse a string 试图做JSON.parse,但它不喜欢我从我的服务器返回的字符串做什么 - Trying to do JSON.parse but it doesnt like what i am doing with a returned string from my server 尝试从内部存储数据使用 JSON.parse 时收到错误 - Receiving error when trying to use JSON.parse from internal storage data 使用 JSON.parse(localStorage.get) 时,LocalStorage getItem 抛出错误“position 1 处的 JSON 中的意外令牌 o” - LocalStorage getItem throwing error “Unexpected token o in JSON at position 1” when use JSON.parse(localStorage.getItem('list')) 在Express的响应上反应JSON.parse语法错误 - React JSON.parse syntax error on response from express JSON.parse localStorage输入错误意外结束 - JSON.parse localStorage unexpected end of input error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM