首页 > 解决方案 > 笑话和酶:如何使用 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 测试此组件的体面方法,我将不胜感激。

标签: reactjstestingjestjsreact-hooksenzyme

解决方案


关于不使用酶浅层有一个未解决的问题。useContext()尝试mount改用。

如果您不想使用 mount,您可以尝试模拟您的 GlobalContext 作为解决方法。这是一篇文章,解释了如何做到这一点。


推荐阅读