我正在尝试为使用 Formik 构建的 React Native 组件编写一些测试。这是一个要求用户名和密码的简单表单,我想使用使用 Yup 构建的验证模式。
当我使用模拟器并手动测试表单时,表单的行为符合预期,仅当输入值无效时才会显示错误消息。
但是,当我尝试使用 编写一些自动化测试时@testing-library/react-native
,行为并不是我所期望的。即使提供的值有效,错误消息也会显示在测试中。下面是代码:
// App.test.js
import React from 'react';
import { render, act, fireEvent } from '@testing-library/react-native';
import App from '../App';
it('does not show error messages when input values are valid', async () => {
const {
findByPlaceholderText,
getByPlaceholderText,
getByText,
queryAllByText,
} = render(<App />);
const usernameInput = await findByPlaceholderText('Username');
const passwordInput = getByPlaceholderText('Password');
const submitButton = getByText('Submit');
await act(async () => {
fireEvent.changeText(usernameInput, 'testUser');
fireEvent.changeText(passwordInput, 'password');
fireEvent.press(submitButton);
});
expect(queryAllByText('This field is required')).toHaveLength(0);
});
// App.js
import React from 'react';
import { TextInput, Button, Text, View } from 'react-native';
import { Formik } from 'formik';
import * as Yup from 'yup';
const Schema = Yup.object().shape({
username: Yup.string().required('This field is required'),
password: Yup.string().required('This field is required'),
});
export default function App() {
return (
<View>
<Formik
initialValues={{ username: '', password: '' }}
validationSchema={Schema}
onSubmit={(values) => console.log(values)}>
{({
handleChange,
handleBlur,
handleSubmit,
values,
errors,
touched,
validateForm,
}) => {
return (
<>
<View>
<TextInput
onChangeText={handleChange('username')}
onBlur={handleBlur('username')}
value={values.username}
placeholder="Username"
/>
{errors.username && touched.username && (
<Text>{errors.username}</Text>
)}
</View>
<View>
<TextInput
onChangeText={handleChange('password')}
onBlur={handleBlur('password')}
value={values.password}
placeholder="Password"
/>
{errors.password && touched.password && (
<Text>{errors.password}</Text>
)}
</View>
<View>
<Button
onPress={handleSubmit}
// If I explicitly call validateForm(), the test will pass
// onPress={async () => {
// await validateForm();
// handleSubmit();
// }}
title="Submit"
/>
</View>
</>
);
}}
</Formik>
</View>
);
}
我不确定我是否正确地编写了测试。我认为 Formik 会在handleSubmit
调用函数时自动验证表单。
在 中App.js
,如果我明确调用validateForm
,测试将通过。onPress
但是,仅仅为了满足测试而改变处理程序的实现是不正确的。也许我错过了围绕这个问题的一些基本概念。任何见解都会有所帮助,谢谢。
软件包版本:
"@testing-library/react-native": "^7.1.0",
"formik": "^2.2.6",
"react": "16.13.1",
"react-native": "0.63.4",
"yup": "^0.32.8"