【问题标题】:React Hook Forms errors testingReact Hook Forms 错误测试
【发布时间】:2022-01-11 15:42:47
【问题描述】:

我想用 Jest 测试来自 react hook 表单的错误。

这是我的输入:

<FormControl
        id="first-name"
        isInvalid={errors.name}
        w={['100%', '100%', '100%']}
      >
        <Input
          name="name"
          placeholder={intl.formatMessage({
            id: 'form.business.name',
            defaultMessage: 'Business name',
          })}
          {...register('name', { required: true })}
        />
        {errors.name && (
          <FormErrorMessage>{errors.name.message}</FormErrorMessage>
        )}
</FormControl>
这就是我试图做的,它不起作用,但你可以了解我想要做什么。

import React from 'react'
import { render, WrapperForm } from '@utils/test-utils'
import { InputName } from '@components/forms/signup/inputs'

describe('InputName Unit Test', () => {
    it('should display correct error message', () => {
      const { getByPlaceholderText } = render(
        <WrapperForm>
          <InputName />
        </WrapperForm>
      )

      fireEvent.click(getByPlaceholderText('Business name'))
      fireEvent.focusOut(getByPlaceholderText('Business name'))

      getByPlaceholderText('Businesss name')

      expect(findByText('name is required').innerHTML).toEqual('name is required')
    })
})

【问题讨论】:

    标签: reactjs jestjs react-testing-library react-hook-form


    【解决方案1】:

    你能分享错误信息吗?

    除此之外,您可能希望使用测试库中的screen 导出来代替查询。

    此外,findBy... 查询默认为async,因此您在使用它们时应使用await

    【讨论】:

    • 错误信息只是一个 div,带有文本'name is required'
    • 我的意思是测试失败消息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2020-06-09
    相关资源
    最近更新 更多