1

如何使用测试库反应原生检查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)
    })
  })
})

但是当我运行这个测试文件时会抛出这样的错误

预期:假接收:未定义

4

1 回答 1

2

我也发生了同样的事情。调试我试过:

expect(getByTestId('button_submit').props).toBe(false)

这显示了 button_submit 拥有的所有道具,实际上它不包含禁用的道具。就我而言,它只有样式和一些内置道具,我不知道为什么:

{"accessible": true, "children": [<Text style={{"color": "#FFFFFF", "fontSize": 16, "fontWeight": "600", "lineHeight": 22, "opacity": 0.3}}>Ingresar</Text>, null], "focusable": true, "isTVSelectable": true, "onClick": [Function bound touchableHandlePress], "onResponderGrant": [Function bound touchableHandleResponderGrant], "onResponderMove": [Function bound touchableHandleResponderMove], "onResponderRelease": [Function bound touchableHandleResponderRelease], "onResponderTerminate": [Function bound touchableHandleResponderTerminate], "onResponderTerminationRequest": [Function bound touchableHandleResponderTerminationRequest], "onStartShouldSetResponder": [Function bound touchableHandleStartShouldSetResponder], "style": {"alignItems": "center", "alignSelf": "stretch", "backgroundColor": "rgba(42, 118, 217, 0.3)", "borderColor": "#FFFFFF", "borderRadius": 16, "borderWidth": 0, "justifyContent": "center", "opacity": 1, "padding": 12}, "testID": "login-submit-button"}

由于启用/禁用按钮的样式不同,我最终测试了按钮的样式,但我仍然希望有更好的解决方案。

expect(submitButton.props.style).toMatchObject({ backgroundColor: 'blue' });

编辑:

我刚刚发现这存在: https ://github.com/testing-library/jest-native

太棒了!例如,它包含以下内容:

expect(getByTestId('button')).toBeDisabled();

.

于 2020-09-24T18:12:10.533 回答