reactjs - 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);
});
解决方案
我建议使用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.
});
});
});
推荐阅读
- java - 如果在不同的接口中声明相同的方法并实现多重继承,jvm 不会混淆
- angular - 在同一 onclick 函数调用中使用 ngIf 时添加/删除子组件
- rust - 为什么存在对 rust 中复制类型的不可变引用?
- amazon-web-services - SQS 从队列中接收丢失的消息
- python - 如何修复 AttributeError:“Matrix”对象没有“clear”属性?
- regex - 正则表达式排除某些内容并批量重命名文件
- elasticsearch - 将数据从 logtsash 推送到 elasticserach
- uml - 我应该使用哪种类型的关系?
- javascript - 博主随机发帖显示,防止无帖子死循环
- angular - 如何解决 Angular TypeError:无法读取未定义的属性“名称”