reactjs React测试库与Next.Js,单元测试因状态而失败?

j2qf4p5b  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(212)

我尝试在我的nextjs应用程序中使用react测试库+ jest创建一个单元测试,这是一个简单的测试,一旦点击按钮而没有填充字段,它应该显示一个错误消息“请输入所有字段”,但我无法找到按钮被点击后的错误消息,我认为这可能与状态有关,因为一旦单击按钮,将设置error true以显示消息。
我的寄存器组件:

import Head from "next/head";
import { useState } from "react";

const Register = () => {
  const [error, setError] = useState(false);
  const [showPass, setShowPass] = useState(false);

  const handleSubmit = async (event: React.SyntheticEvent) => {
    event.preventDefault();

    const name = (event?.target as any).nome?.value;
    const email = (event?.target as any).email?.value;
    const password = (event?.target as any).password?.value;

    if (name === "" || email === "" || password === "") {
      setError(true);
      return;
    }

    const data = {
      name,
      email,
      password,
    };

    const resp = await fetch("http://localhost:5000/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    const data2 = await resp.json();
  };

  return (
    <div className="center text-textLight">
      <Head>
        <title>Forum</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <h2 className="title mb-8">Register</h2>
      {error && <h2 className="text-error">Please enter all fields</h2>}
      <form onSubmit={handleSubmit}>
        <div>
          <input
            className="inputStyle mb-2"
            type="text"
            name="nome"
            placeholder="name"
          />
        </div>
        <div>
          <input
            className="inputStyle mb-2"
            type="text"
            name="email"
            placeholder="email"
          />
        </div>
        <div>
          <div>
            <input
              className="inputStyle dark:text-textLight"
              type={showPass ? "text" : "password"}
              name="password"
              placeholder="password"
            />
          </div>
          <div className="mt-2 flex items-center justify-center">
            <input
              onChange={() => setShowPass((prev) => !prev)}
              className="mr-2"
              type="checkbox"
              id="showPas"
              name="showPas"
            />
            <label className="dark:text-textDark" htmlFor="showPas">
              Show password
            </label>
          </div>
        </div>

        <button className="btn mt-6 dark:text-textDark">Submit</button>
      </form>
    </div>
  );
};

export default Register;

我的注册测试:

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Register from "../src/pages/register";

test("should show error message if username and password is empty", async () => {
  const user = userEvent.setup();

  render(<Register />);

  await user.click(screen.getByRole("button", { name: /submit/i }));

  expect(screen.findByTestId("error")).toHaveTextContent(
    "Please enter all fields"
  );
});

jest.congif.js

const nextJest = require("next/jest");

const createJestConfig = nextJest({
  dir: "./",
});

/** @type {import('jest').Config} */
const customJestConfig = {
  moduleDirectories: ["node_modules", "src"],
  testEnvironment: "jest-environment-jsdom",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
};

module.exports = createJestConfig(customJestConfig);


jest.setup.js

import "@testing-library/jest-dom/extend-expect";
import "@testing-library/user-event";
2ul0zpep

2ul0zpep1#

在这里,您尝试查找一个testid = error. expect(screen.findByTestId("error")).toHaveTextContent("Please enter all fields");的元素
要通过此语句获取的元素是<h2 className="text-error">Please enter all fields</h2>
它没有testid。请参见https://testing-library.com/docs/queries/bytestid/
<h2 className="test-error" data-testid="error">Please enter all fields</h2>也是如此
以便能够通过TestId选择此元素。
但是,正如您将在byTestId的文档中看到的那样,不推荐使用它。在这种特殊情况下,我建议使用getByText。
以及实施

expect(screen.getByText("Please enter all fields")).toBeInTheDocument()

相关问题