测试库 React Native

Posted

技术标签:

【中文标题】测试库 React Native【英文标题】:Testing Library React Native 【发布时间】:2020-10-06 11:04:45 【问题描述】:

如何使用测试库反应原生检查 formik 表单中的禁用按钮? 这是我的表单js。在这个表单中,我有文本输入会testId input_email,如果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)
    )
  )
)

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

预期:false 接收:未定义

【问题讨论】:

【参考方案1】:

这也发生在我身上。调试我试过:

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();

?。 ??

【讨论】:

多年来我一直在寻找一种在控制台中打印道具的方法。你会认为 api 会有这样的东西。 我只使用 console.log(myComponent.props) ?

以上是关于测试库 React Native的主要内容,如果未能解决你的问题,请参考以下文章

React 测试库覆盖延迟加载

React 测试库:测试属性/prop

React 测试库:测试样式(特别是背景图片)

在 React 测试库中测试依赖于 Stateful Context Providers 链的 React 组件

使用 React 测试库获取 HTML 元素?

为 create-react-app 添加 React 测试库时出错(版本 16.12.0)