SaveButton 已禁用,并且 isValid 在等待 user.type 成功后仍处于禁用状态

问题描述 投票:0回答:1

我测试了我的 SimpleForm,但即使在成功写入输入后,我的 SaveButton 仍然被禁用(包含 className 'Mui-disabled')。

npm 包在这里很有用:

  • 访问测试:0.34.1
  • 反应钩子形式:7.45.2
  • 反应管理:4.11.0
  • 测试库/反应:14.0.0
  • 反应:18.2.0

工具栏:

const SaveCancelDeleteToolbar = (props: SaveCancelDeleteToolbarProps) => {
  const { closeDrawer, handleCancel } = props

  const translate = useTranslate()

  const {
    formState: { isValid },
  } = useFormContext()

  return (
    <Toolbar>
      <SaveButton disabled={!isValid} onClick={closeDrawer} />
      <Button onClick={handleCancel}>{translate('ra.action.cancel')}</Button>
    </Toolbar>
  )
}

形式:

<SimpleForm mode="all" reValidateMode="onChange" toolbar={toolbar}>
  <TextInput
    data-testid="form.value"
    label="resources.values.fields.value"
    source="value"
    validate={[required(), maxLength(50), noEmptySpace]}
  />
</SimpleForm>

为了防止测试环境中的react-hook-form崩溃,我必须使用包装器来添加

const formMethods = useForm()

测试文件:

it('should be able to create element', async () => {

// ValueList contains somewhere the SimpleForm.
const { user, ...utils } = setup(
  <FormContextWrapper resource="vat-rates">
    <ValueList deleted={false} />
  </FormContextWrapper>
)

/* Some code that open my SimpleForm **/

// Check that SaveButton is disabled when pristine
const saveButton = await screen.findByText('ra.action.save')
expect(saveButton.outerHTML.includes('Mui-disabled')).toBe(true)

const divValue = await screen.findByTestId(
        'form.value'
      )
const inputValue = divValue.children[1].children[0]

fireEvent.focus(inputValue )
await user.type(inputValue , '1')
fireEvent.blur(inputValue )

// This expect is successful, my input has been set to '1'.
expect(inputValue.value).toBe('1')

await waitFor(() => {
  const saveButton2 = screen.getByText('ra.action.save')
  // This expect fails. saveButton2 exist.
  // Its outerHTML is the following. In react-admin I saw that in DOM, disabled is always "" so I check with 'Mui-disabled' presence.
  // `<button class="LotsOfClasses Mui-disabled" tabindex="-1" type="submit" disabled="" aria-label="ra.action.save">ra.action.save</button>`
  expect(saveButton2.outerHTML.includes('Mui-disabled')).toBe(false)
})

})

由于未知原因,SaveCancelDeleteToolbar 组件未在测试环境中重新渲染。因此 isValid 保持 false 并且 SaveButton 仍然具有“Mui-disabled”className。

请帮忙,测试表单是一个非常重要的过程,不能忽视。

reactjs react-testing-library react-hook-form react-admin vitest
1个回答
0
投票

正如@slax57所说,这是有问题的包装器解决方法。

出于我仍然未知的原因,在测试环境中“正在加载react-hook-form的esm和更改版本”。

解决方案是将以下行添加到

vite.config.js
文件中。

resolve: {

    alias: {

      'react-hook-form': require.resolve('react-hook-form'),

    }

  }
© www.soinside.com 2019 - 2024. All rights reserved.