首页 > 解决方案 > React jest 如何测试基于 localStorage 项的 Redirect

问题描述

我有一个组件检查本地存储密钥,并根据它决定是渲染组件还是重定向到登录屏幕。

我想使用 jest 和酶来测试这个案例,但我无法强制代码使用模拟 localstorage 而不是实际的浏览器 locastorage。

现在编码它试图读取本地存储,它总是得到空值。

我已经花了 2-3 个小时并关注了许多 stackobverflow 问题,但他们中的大多数人都在尝试模拟 localstorage 并检查它是否从假的 localstorage 中设置和读取值。

我认为我的情况不同,因为我想伪造本地存储,但该输出应该会影响组件决策。

下面是我的组件代码

        // Below console.log prints null when i run test, which i think should print { "googleId" : null} , isnt it ?
        console.log(localStorage.getItem("auth")); 
        let storageUser = JSON.parse(localStorage.getItem("auth"));
        if (!storageUser || !storageUser.googleId){
            return <Redirect to="/login" />
        }

        return (
            <Home user  = {user} />
        )
    }

和我的测试代码

it("Renders Home page if googleId is set in localStorage", () => {
    const localStorage = jest.fn();
    global.localStorage.getItem = key => '{ "googleId" : null}';

    // Below code prints { "googleId" : null}
    console.log(localStorage.getItem("auth"));

    expect(wrapper.find(Home).length).toEqual(1);
});

标签: reactjsunit-testingjestjsenzyme

解决方案


我建议使用jest-localstorage-mock - 设置过程应该不难。

通过在测试中包含包,您可以访问可以轻松操作的模拟 LS,例如:

localStorage.__STORE__["auth"] = your_desired_object;

这是一个可能适合您的问题的简短示例 - 它也是在以下情况下测试不同条件的演示:

beforeEach(() => {
   // According to the documentation: "values stored in tests will also be available in other tests unless you run"
   localStorage.clear();
});

describe("when `auth` does not exist in the localStorage", () => {
   it("redirects the user to the `login` page", () => {
      // ...
   });
});

describe("when `auth` exists in the localStorage", () => {
   describe("when `googleId` is not defined", () => {
      it("redirects the user to the `login` page", () => {
         // ...
      });
   });

   describe("when `googleId` is defined", () => {
      it("renders `Home`", () => {
        // Ensures if the `Home` page is rendered if the last circumstance occurs.
      });
   });
});

推荐阅读