【发布时间】:2022-11-18 00:38:40
【问题描述】:
我希望为 LoginForm 触发提交处理程序。我将 MUI 与 Formik 一起使用。我正在尝试模拟提交处理程序,但“handleSubmit”处理程序永远不会被解雇。我如何确保我的模拟处理程序被调用?
有没有办法做到这一点??
const Login = () => {
const handleSubmit = async (values: any) => {
..... // submit logic
};
return (
<Grid item xs={12}>
<Formik
initialValues={{
username: '',
password: '',
submit: null
}}
validationSchema={LoginValidationSchema}
onSubmit={handleSubmit}
>
{({ errors, handleBlur, handleChange, handleSubmit, isSubmitting, touched, values }) => (
<form data-testid="login-form" noValidate onSubmit={handleSubmit}>
<FormControl fullWidth error={Boolean(touched.username && errors.username)}>
<InputLabel htmlFor="username">Email Address / Username</InputLabel>
<OutlinedInput
id="username"
type="email"
value={values.username}
name="username"
onBlur={handleBlur}
onChange={handleChange}
label="Email Address / Username"
inputProps={{}}
/>
{touched.username && errors.username && (
<FormHelperText error id="helper-text-username">
{errors.username}
</FormHelperText>
)}
</FormControl>
<FormControl fullWidth error={Boolean(touched.password && errors.password)}>
<InputLabel htmlFor="password">Password</InputLabel>
<OutlinedInput
id="password"
type="password"
value={values.password}
name="password"
onBlur={handleBlur}
onChange={handleChange}
label="Password"
inputProps={{}}
/>
{touched.password && errors.password && (
<FormHelperText error id="helper-text-password">
{errors.password}
</FormHelperText>
)}
</FormControl>
{errors.submit && (
<Box>
<FormHelperText error>{errors.submit}</FormHelperText>
</Box>
)}
<Box>
<Button
data-testid="login"
disableElevation
disabled={isSubmitting}
fullWidth
size="large"
type="submit"
variant="contained"
>
Sign in
</Button>
</Box>
</form>
)}
</Formik>
</Grid>
)
};
export default Login;
到目前为止我尝试了什么:
const onSubmit = jest.fn();
const { getByTestId, getLabelByText } = wrapper;
formData = { email: 'username', password: 'password' };
emailInput = getByLabelText('Email Address / Username');
passwordInput = getByLabelText('Password');
loginButtonNode = wrapper.getByText('Sign in') as HTMLElement;
await waitFor(() => {
fireEvent.change(emailInput, { target: { value: formData.email } });
fireEvent.change(passwordInput, { target: { value: formData.password } });
});
act(() => {
fireEvent.click(getByTestId('login'));
});
// throws error
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
username: 'username,
password: 'password'
});
});
// throws error
await waitFor(() => {
expect(onSubmit).toHaveBeenCalled()
});
// throws error
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledTimes(1)
});
任何帮助,将不胜感激。
【问题讨论】:
标签: reactjs jestjs react-testing-library