【问题标题】:jest and enzyme: how to test component with useContext()笑话和酶:如何使用 useContext() 测试组件
【发布时间】: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


    【解决方案1】:

    有一个 open issue 关于 useContext() 不使用酶浅层。尝试改用mount

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

    【讨论】:

    猜你喜欢
    • 2019-04-05
    • 2018-08-24
    • 2018-03-23
    • 2022-07-04
    • 2019-09-13
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多