【发布时间】:2020-06-14 16:38:59
【问题描述】:
我需要测试以下组件(基本上我想在用户名和刷新令牌存在时测试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 测试这个组件的好方法,我将不胜感激。
【问题讨论】:
标签: reactjs testing jestjs react-hooks enzyme