【问题标题】:React Testing Library: Render method always returns <body><div/></body>, not the actual contentReact 测试库:Render 方法总是返回 <body><div/></body>,而不是实际内容
【发布时间】:2022-12-29 22:07:53
【问题描述】:

我是 React 测试库的新手。我想测试位于 Login.tsx 组件内的登录表单。

`

const Login = () => {
  useYupTranslation();
  const dispatch = useAppDispatch();
  const { t } = useTranslation(["common", "loginPage", "buttons", "loginPage"]);
  useDocumentTitle(t("loginPage:header"));
  const navigate = useNavigate();
  const location = useLocation();
  const token = getTokenFromLocalStorage();
  const refreshToken = getRefreshTokenFromLocalStorage();
  const currentTime = new Date().getTime();
  const decodedAccessToken = decodeToken<DecodedToken["accessToken"]>(token!);
  const decodedRefreshToken = decodeToken<DecodedToken["refreshToken"]>(refreshToken!);
  useEffect(() => {
    if (location.search === "?token-expired") {
      toast.error(t("loginPage:logoutNotification"), {
        autoClose: false,
      });
    }
  }, [location, t, token]);

  const loginValidation = Yup.object({
    email: Yup.string().email().required(),
    password: Yup.string().required(),
  });
  const loginFormik = useFormik({
    initialValues: {
      email: "",
      password: "",
    },
    onSubmit: async (values) => {
      await dispatch(loginUser(values));
      navigate(`${location.state ? location.state : "/start"}`);
    },
    validationSchema: loginValidation,
  });
  if (
    token &&
    decodedAccessToken &&
    currentTime / 1000 < decodedAccessToken.exp &&
    decodedRefreshToken &&
    currentTime / 1000 < decodedRefreshToken.exp
  ) {
    return <Navigate to={`${location.state ? location.state : "/start"}`} />;
  }
  return (
    <BasePageLayout img={<Logo width={"100%"} />}>
      <Box
        boxShadow={3}
        maxWidth={800}
        marginY="0.5rem"
        sx={{
          display: "flex",
          backgroundColor: "common.white",
          borderTop: 5,
          borderColor: "primary.main",
          borderRadius: "8px 8px 0px 0px",
        }}
      >
        <Box padding={2}>
          <FormikProvider value={loginFormik}>
            <form onSubmit={loginFormik.handleSubmit} style={{ maxWidth: "520px" }}>
              <Grid container columnSpacing={2} rowSpacing={2.5}>
                <Grid item xs={12} sm={12} md={12} minHeight="100px">
                  <TextFieldFormik id="email" label={t("common:form.email")} name="email" />
                </Grid>
                <Grid item xs={12} sm={12} md={12} minHeight="100px">
                  <PasswordFieldFormik
                    id="password"
                    label={t("common:form.password")}
                    name="password"
                  />
                </Grid>
              </Grid>
              <Button
                type="submit"
                isSubmitting={loginFormik.isSubmitting}
                sx={{ marginY: "1rem" }}
              >
                {t("buttons:submit")}
              </Button>
            </form>
          </FormikProvider>       
        </Box>
      </Box>
    </BasePageLayout>
  );
};

export default Login;

Login component is rendered in App.tsx that looks like this:

function App() {
  return (
    <Suspense
      fallback={
        <Box minHeight={"100vh"} display="flex" justifyContent="center" alignItems="center">
          <CircularProgress />
        </Box>
      }
    >
      <MuiThemeProvider theme={theme}>
        <ThemeProvider theme={theme}>
          <BrowserRouter>
            <Routes>
              <Route element={<PrivateRoute />}>
                <Route path="/start" element={<Start />} />
              </Route>
              <Route path="/login" element={<Login />} />
              <Route path="*" element={<NotFoundPage />} />
            </Routes>
          </BrowserRouter>
          <ToastContainer position="top-center" />
        </ThemeProvider>
      </MuiThemeProvider>
    </Suspense>
  );
}

export default App;

` 当我尝试在 Login.test.tsx 文件中呈现 Login.tsx 组件时,它只是返回 body 标签内的 div(不是实际组件的内容),所以我什至无法访问表单输入或提交按钮进行测试他们。

登录.test.tsx:

import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import Login from "../views/Login";

it("should render input elements", () => {
  render(<Login />);
  
  screen.debug();
});

screen.debug() 的输出只是:

<body>
 <div/>
</body>

我怎样才能访问登录组件的实际内容?除了 NotFoundPage 之外的其他组件也会发生同样的事情。

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

    我遇到了同样的问题,而且奇怪的是,如果我测试我的路线,它会按应有的方式呈现。只有当我尝试自己渲染一个组件时,它才不起作用。我刚刚从 v16 迁移到 React v18。在 v16 测试中,这不是问题。据我所知,我根据反应文档更新了所有需要的开发依赖项。如果您找到了解决方案,您介意分享吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 2011-05-18
      相关资源
      最近更新 更多