Reactjs jest和Ezyme:如何使用useContext()测试组件
我需要测试以下组件(基本上,我想在用户名和刷新令牌存在时测试应用程序组件的存在):Reactjs jest和Ezyme:如何使用useContext()测试组件,reactjs,testing,jestjs,react-hooks,enzyme,Reactjs,Testing,Jestjs,React Hooks,Enzyme,我需要测试以下组件(基本上,我想在用户名和刷新令牌存在时测试应用程序组件的存在): constparentrouter=()=>{ const{username,refreshtToken}=useContext(GlobalContext); 返回( {console.log(“test1”)} {console.log(“test2”)} ); }; 这是我迄今为止的尝试: const TestProtectedRouteWithCredentials = () => ( <
constparentrouter=()=>{
const{username,refreshtToken}=useContext(GlobalContext);
返回(
{console.log(“test1”)}
{console.log(“test2”)}
);
};
这是我迄今为止的尝试:
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);
});
const TestProtectedRouteWithCredentials=()=>(
);
测试(“如果用户名和道具允许重定向到受保护的路由,即应用程序)”,()=>{
常量包装器=浅();
期待(
包装纸
.find(父路由器)
.潜水
.查找(应用程序)
).toHaveLength(1);
});
但我似乎无法让它工作
TypeError:无法对“undefined”或“null”的属性username
进行分解
我四处搜寻了一下,但没有真正找到我要找的东西。如果有人能给我展示一种使用Jest和Ezyme测试该组件的好方法,我将不胜感激。有一个关于useContext()
不使用Ezyme的问题。尝试使用挂载
如果您不想使用mount,可以尝试将GlobalContext模拟为一种解决方法。这里将解释如何做到这一点。这里有一个关于useContext()
不使用的问题。尝试使用挂载
如果您不想使用mount,可以尝试将GlobalContext模拟为一种解决方法。以下是如何操作的说明。我在使用
挂载时遇到同样的问题:我在使用挂载时遇到同样的问题:
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);
});