我正在学习如何测试反应形式,我不明白为什么我的测试没有成功?
Expected: {"email": "john.dee@someemail.com", "firstName": "John", "lastName": "Dee", "password": "password"}
Number of calls: 0
我的表格很简单:
const SignUpForm = () => {
const formik = useFormik({
initialValues: initialValues,
validationSchema: schema,
onSubmit: submitForm,
});
return (
<form onSubmit={formik.handleSubmit}>
<label htmlFor="firstName">First Name</label>
< input ..>
<label htmlFor="lastName">Last Name</label>
< input ..>
<label htmlFor="password">password</label>
< input ..>
<label htmlFor="email">Email</label>
< input ..>
<button type="submit">Submit</button>
</form>
);
};
export default SignUpForm;
以及测试:
test("rendering and submitting a basic Formik form", async () => {
const handleSubmit = jest.fn();
render(<SignUpForm onSubmit={handleSubmit} />);
userEvent.type(screen.getByLabelText(/First Name/i), "John");
userEvent.type(screen.getByLabelText(/Last Name/i), "Dee");
userEvent.type(screen.getByLabelText(/Email/i), "john.dee@someemail.com");
userEvent.type(screen.getByLabelText(/password/i), "password");
userEvent.click(screen.getByRole("button", { name: /Submit/i }));
await waitFor(() =>
expect(handleSubmit).toHaveBeenCalledWith({
email: "john.dee@someemail.com",
firstName: "John",
lastName: "Dee",
password: "password",
})
);
});
我确实出口了";initialValues"模式";以及";onsubmit";在其他文件中,当我测试自己时,一切似乎都正常工作。
在控制台中,当测试完成时,我可以看到我的表单,其中所有值都填写了:
<input id="email" name="email" type="email" value="john.dee@someemail.com" />
更新:这里有一个包含所有相关代码的链接:https://pastebin.com/CbpFFzf4
您的SignUpForm
没有onSubmit道具。
如果onSubmit
来自另一个文件,则应该模拟该模块中的函数。
import * as HelperFunctions from './submitForm.js'
在测试开始时,您可以监视该功能。
jest.spyOn(HelperFunctions, 'onSubmit')
然后你可以测试它是否被这样调用。
expect(HelperFunctions.onSubmit).toHaveBeenCalledWith({
email: "john.dee@someemail.com",
firstName: "John",
lastName: "Dee",
password: "password",
})
确保已导出函数。