如何使用测试库反应原生检查formik表单中的禁用按钮?这是我的表单js。在这个表单中,我有文本输入会 testId input_email,如果电子邮件无效,按钮提交应该被禁用。
/* eslint-disable indent */
import * as yup from 'yup'
import { Formik } from 'formik'
import React, { Component, Fragment } from 'react'
import { TextInput, Text, Button, Alert } from 'react-native'
export default class App extends Component {
render() {
return (
<Formik
initialValues={{ email: '', password: '' }}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={yup.object().shape({
email: yup
.string()
.email('Enter a valid email')
.required('Email is required'),
password: yup
.string()
.min(6, 'Password must have at least 6 characters')
.required('Password is required')
})}>
{({
values,
handleChange,
errors,
setFieldTouched,
touched,
isValid,
handleSubmit
}) => (
<Fragment>
<TextInput
testID={'input_email'}
value={values.email}
onChangeText={handleChange('email')}
onBlur={() => setFieldTouched('email')}
placeholder="E-mail"
/>
{touched.email && errors.email && (
<Text testID={'error_email'} style={{ fontSize: 10, color: 'red' }}>{errors.email}</Text>
)}
<TextInput
testID={'input_password'}
value={values.password}
onChangeText={handleChange('password')}
placeholder="Password"
onBlur={() => setFieldTouched('password')}
secureTextEntry={true}
/>
{touched.password && errors.password && (
<Text testID={'error_password'} style={{ fontSize: 10, color: 'red' }}>
{errors.password}
</Text>
)}
<Button
testID={'button_submit'}
title="Sign In"
disabled={!isValid}
onPress={handleSubmit}
/>
</Fragment>
)}
</Formik>
)
}
}
这是我的测试文件。在这个测试文件中,在 fireEvent changeText 和 blur 之后,会检查 email 输入的值并检查 button_submit
/* eslint-disable no-undef */
/**
* @format
*/
import 'react-native'
import React from 'react'
import renderer from 'react-test-renderer'
import Adapter from 'enzyme-adapter-react-16'
import { shallow, configure } from 'enzyme'
import App from '../App'
import { fireEvent, render, wait, cleanup } from '@testing-library/react-native'
jest.setTimeout(30000)
configure({ adapter: new Adapter(), disableLifecycleMethods: true })
const appWrapper = shallow(<App />)
afterEach(cleanup)
describe('App', () => {
it('should renders correctly', async () => {
renderer.create(<App />)
})
it('should renders text input email and password', () => {
expect(appWrapper.find('[id="input_email"]').exists())
expect(appWrapper.find('[id="input_password"]').exists())
})
test('should be show error if value email is not valid', async () => {
const { getByTestId } = render(<App />)
const input = getByTestId('input_email')
fireEvent.changeText(input, 'ganda.com')
fireEvent.blur(input)
expect(getByTestId('input_email').props.value).toEqual('ganda.com')
await wait(() => {
expect(getByTestId('error_email').props.children).toEqual('Enter a valid email')
expect(getByTestId('button_submit').props.disabled).toBe(false)
})
})
})
但是当我运行这个测试文件时会抛出这样的错误
预期:假接收:未定义