我正在尝试测试提交表单的组件:
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
尝试将 .preventdefault() 与 if else 语句一起使用?我不确定,但这应该可以阻止您遇到的点击问题,如果您使用 if else 语句,您可以添加代码来阻止无效电子邮件问题。希望这有帮助
看起来这是 JSDOM 中与依赖的react-testing-library相关的一个未解决的问题:https://github.com/testing-library/react-testing-library/issues/729
但是您可以在提交处理程序中检查最重要的验证错误,确认所有必需的值都已通过,或者如果缺少则提前返回。