尽管在使用 jest 进行单元测试期间无效,但仍在提交表单 - React

问题描述 投票:0回答:2

我正在尝试测试提交表单的组件:

  • 该组件需要“onSubmit”功能。
  • 它包括一个类型设置为“电子邮件”的输入字段。 当我尝试提交无效电子邮件时,浏览器会阻止提交并显示错误消息: browser preventing me from submitting an invalid email 但是,当我在测试中复制相同的操作时,它会失败,因为即使电子邮件无效(不应调用“onSubmit”函数),也会调用模拟的“onSubmit”函数。 下面是我的组件和我正在使用的 Jest 测试的精简版本 成分:
interface AppProps {
  onSubmit: () => Promise<any>;
  onComplete: (data: any) => void;
}

function App(props: AppProps) {
  function handleSubmit(event: any) {
    event.preventDefault();

    props.onSubmit().then((response) => {
      props.onComplete(response);
    });
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email"> Email </label>
      <input id="email" type="email" required />
      <button> Submit </button>
    </form>
  );
}

export default App;

测试:

import { fireEvent, render, screen } from "@testing-library/react";
import App from "./App";

test("Invalid form isn't submitted", async () => {
  const onSubmit = jest.fn();
  onSubmit.mockResolvedValue("");

  const onComplete = jest.fn((value) => {
    console.log("Function called");
  });

  render(<App onSubmit={onSubmit} onComplete={onComplete} />);

  const input = screen.getByLabelText("Email");
  fireEvent.change(input, { target: { value: "invalid" } });

  const button = screen.getByText("Submit");  
  fireEvent.click(button);

  expect(onSubmit).not.toBeCalled();
});

这是 npm run test 的输出 失败 src/App.test.tsx ● 无效表单未提交 期望(jest.fn()).not.toBeCalled() 预计通话次数:0 接听电话数量:1

reactjs typescript unit-testing testing jestjs
2个回答
0
投票

尝试将 .preventdefault() 与 if else 语句一起使用?我不确定,但这应该可以阻止您遇到的点击问题,如果您使用 if else 语句,您可以添加代码来阻止无效电子邮件问题。希望这有帮助


0
投票

看起来这是 JSDOM 中与依赖的react-testing-library相关的一个未解决的问题:https://github.com/testing-library/react-testing-library/issues/729

但是您可以在提交处理程序中检查最重要的验证错误,确认所有必需的值都已通过,或者如果缺少则提前返回。

© www.soinside.com 2019 - 2024. All rights reserved.