Jest.js 如何编写单元测试用例进行复选框的错误验证

dkqlctbz  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(147)

我有一个场景,当用户在没有同意条款的情况下点击Next按钮时,我应该抛出一个错误,说'请同意条款',所以我需要使用Jest和React测试库为它编写一个单元测试用例。我如何才能实现这一点。

import Terms from "./Terms";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <Terms />
    </div>
  );
}
const { useState } = require("react");

function Terms() {
  const [checked, setChecked] = useState(false);
  const [errorMessage, setErrorMessage] = useState(false);
  const onNext = (e: React.FormEvent) => {
    e.preventDefault();
    if (checked !== true) {
      setErrorMessage(true);
    } else {
      setErrorMessage(false);
    }
  };
  const handleCheckBoxChange = (e: React.FormEvent) => {
    const result = (e.target as HTMLInputElement).checked;
    setChecked(result);
  };

  return (
    <div>
      <h1>Terms</h1>
      <input type="checkbox" value={checked} onChange={handleCheckBoxChange} />
      <label>click to agree the terms</label>
      <br />
      {errorMessage && <p>Please agree the terms before proceeding</p>}
      <button onClick={onNext}>Next</button>
    </div>
  );
}
export default Terms;
acruukt9

acruukt91#

好吧,先把它分解一下。你需要一个测试,它一个接一个地做以下事情:
1.渲染Terms组件
1.找到标记为“下一步”的按钮
1.单击按钮
1.在屏幕上查找错误文本
你可以使用react-testing-library来获取你需要的元素,使用user-event-testing-library来与它们交互。
将这两个库作为依赖项添加到项目中,并尝试以下操作,导入使其工作所需的内容:

it("error shows when terms not agreed", async () => {
  const user = userEvent.setup();

  render(<Terms />)

  const nextButton = screen.getByRole("button", { name: /next/i });
  await user.click(nextButton);
  
  expect(screen.getByText(/please agree the terms before proceeding/i)).toBeVisible()
})

您可能也希望对您的快乐案例进行类似的测试,即在单击按钮之前同意条款。

相关问题