[英]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.