我正在尝试测试一个提交表单的组件:
- 该组件需要“onSubmit”函数。
- 它包括一个输入字段,其类型设置为“email”。当我尝试提交无效电子邮件时,浏览器阻止提交并显示错误消息: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的输出FAIL src/App.test.tsx ● Invalid form isn 't submitted expect(jest.fn()).not.toBeCalled()预期调用次数:0已接来电数:1
1条答案
按热度按时间xkftehaa1#
尝试使用.preventdefault()和if else语句?我不确定,但这应该停止点击问题,你有,如果你使用一个if else语句,你可以添加代码来停止无效的电子邮件问题。希望这有帮助