reactjs - 笑话和酶:如何使用 useContext() 测试组件
问题描述
我需要测试以下组件(基本上我想在用户名和刷新令牌存在时测试 App 组件的存在):
const ParentRouter = () => {
const { username, refreshToken } = useContext(GlobalContext);
return (
<Switch data-test="component-ParentRouter">
{console.log("test1")}
<Route path="/login" component={LoginPage} />
<Route path="/forgotpassword" component={LoginPage} />
{console.log("test2")}
<ProtectedRoute
isAllowed={refreshToken}
username={username}
path="/"
component={App}
/>
</Switch>
);
};
这是我迄今为止的尝试:
const TestProtectedRouteWithCredentials = () => (
<MemoryRouter initialEntries={["/ProjectsOverview/"]}>
<GlobalContext.Provider
value={{
username: "testUser1",
refreshToken: "hfsjkadhfjkshdfjkshdafs"
}}
>
<ParentRouter />
</GlobalContext.Provider>
</MemoryRouter>
);
test("if userame and props then allow redirect to protected route i.e. app", () => {
const wrapper = shallow(<TestProtectedRouteWithCredentials />);
expect(
wrapper
.find(ParentRouter)
.dive()
.find(App)
).toHaveLength(1);
});
我似乎无法让它工作。
TypeError:无法解构
username
“未定义”或“空”的属性。
我已经四处搜索,但没有真正找到我要找的东西。如果有人可以向我展示一种使用 Jest 和 Enzyme 测试此组件的体面方法,我将不胜感激。
解决方案
推荐阅读
- spring-cloud-gateway - 在 Spring Cloud 的 GatewayFilter 中注入 bean
- r - 仅当特定值不使用 r 时才绑定表
- reactjs - .NetCore React JS:如何防止 .gltf 文件被路由?
- xml - 如何在 SSIS 中编辑 WSDL (XML)
- javascript - 多选功能中的值显示不正确
- python - 我需要编写一个函数,该函数返回一个数字在另一个列表中出现次数的列表
- javascript - 向节点 js 发送发布请求时,我得到一个空对象
- wordpress - 预加载器不会在移动设备上停止 - wordpress
- python - 如何将列表中的字符串类型字典转换为字典
- python - Django 发送电子邮件错误:ConnectionRefusedError:[Errno 61] 连接被拒绝